Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
172
rated 0 times [  177] [ 5]  / answers: 1 / hits: 45786  / 12 Years ago, sun, december 9, 2012, 12:00:00

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.


More From » html

 Answers
3

I'm using this solution, which automatically sets the border.



http://jsfiddle.net/aLz2T/3/



HTML



<div><span>1</span><span>2</span><span>3</span><span>4</span></div>​


CSS



div {
width: 204px; /* adjust to get less/more columns */
}

span {
display: inline-block;
height: 100px;
width: 100px;
border: 1px solid #ccc;
border-left-width: 0;
border-top-width: 0;
}​


JavaScript



var a = document.querySelector('div');

// columns
var b = parseInt(a.offsetWidth / (100 + 2), 10);

for(var c, d = document.querySelectorAll('span'), e = d.length, i = 0; c = d[i]; i++) {
// column
c.style.borderRightWidth = ((i + 1) % b) != 0 ? 1px : 0;
// row
c.style.borderBottomWidth = parseInt(i / b, 10) * b < e - b ? 1px : 0;
}​

[#81519] Friday, December 7, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ashli

Total Points: 210
Total Questions: 94
Total Answers: 96

Location: Austria
Member since Sat, Jul 24, 2021
3 Years ago
;