I'd like to use the CSS border
attribute to make a fine 1px
grid between span
elements, like so.
|
1 | 2
-----|-----
3 | 4
|
This is what I currently have. It doesn't quite work obviously.
<html>
<head>
<style>
div {
width: 204px;
}
span {
display: inline-block;
height: 100px;
width: 100px;
border: 1px solid #ccc;
border-left-width: 0;
border-top-width: 0;
}
</style>
</head>
<body>
<div><span>1</span><span>2</span><span>3</span><span>4</span></div>
</body>
</html>
When the div
is set to 306px
and the elements reflow, the solution should adapt dynamically.
| |
1 | 2 | 3
-----|-----|-----
4 |
|
Preferably CSS only, or pure Javascript. Older browsers like IE7 can be ignored.
1. HTML+CSS solution
HTML:
CSS:
DEMO: http://jsfiddle.net/HTgKJ/
2. HTML+CSS+JavaScript solution
HTML+CSS:
JavaScript:
DEMO: http://jsfiddle.net/HTgKJ/1/
I'm using this solution, which automatically sets the border.
http://jsfiddle.net/aLz2T/3/
HTML
CSS
JavaScript
I came up with this approach, which I think works pretty well with minimal CSS and hacks: https://codepen.io/eriklharper/pen/JMKMqa
It introduces an extra wrapping element around the whole grid (which isn't perfect either) but I've found this to be a worthwhile compromise, despite. The lack of ability to simply style the
grid-gap
s directly is a shortcoming with CSS Grid that should be addressed with the spec.Here you can find my solution with jQuery. http://jsfiddle.net/UZJmd/7/
You just jave to put how many spans you want and then define the number of columns you want. Everything else is defined dinamically.
In line 3 we define the number of columns we want. In line 10 we check if it's the last span of the line and we set the right border to 0. In line 14 we check if we are in the last line and then set the bottom border to 0.
If you're looking for a solution without JavaScript that works with an irregular amount of "table cells" I've created a solution with css
border
and pseudo-classes.See this post here: https://stackoverflow.com/a/49309785/6560093