Remove bottom margin of last the "row" of floating <li> elements
To better control vertical spacing on a page, this code eliminates the bottom margins of the <li> elements that fall on the last "row".
by Matthew Day
HTML
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
<div class="description">Array of values showing the top x-coordinate of each element above:
<p id="result"></p>
</div>
CSS
body {
color: #666;
font-family: 'arial', sans-serif;
}
ul {
background: thistle;
list-style: none;
}
ul:after {
content: ".";
visibility: hidden;
display: block;
height: 0;
clear: both;
}
li {
background: navy;
float: left;
height: 26px;
margin: 0 8px 8px 0;
width: 70px;
}
.nomargin {
background: crimson;
margin-bottom: 0;
}
.description {
margin: 0 auto;
width: 90%;
}
p {
margin-top: 8px;
}
JavaScript
// Create an array that contains the top x-coordinate of each item
var items = function() {
var myVar = document.querySelectorAll('li'),
bodyRect = document.body.getBoundingClientRect(),
myArray = [];
for(var i = 0; i < myVar.length; i++) {
var elemRect = myVar[i].getBoundingClientRect(),
offset = elemRect.top - bodyRect.top;
myArray.push(offset);
}
return myArray;
}
// Get the last value of the array, which in this case will always be the highest (the highest value is what we really want)
var last = function() {
var myVar = items(),
myLast = myVar[myVar.length-1];
return myLast;
}
// Check to see which elements match the highest value and apply a 'nomargin' class to the ones that do.
var match = function() {
var myVar = document.querySelectorAll('li'),
bodyRect = document.body.getBoundingClientRect(),
myTarget = last();
for(var i = 0; i < myVar.length; i++) {
var elemRect = myVar[i].getBoundingClientRect(),
offset = elemRect.top - bodyRect.top;
if(myTarget === offset) {
myVar[i].className += 'nomargin';
} else {
}
}
}
var result = document.getElementById('result');
result.innerHTML = items();
match();
//Figure out how to incorporate this later
//window.onresize = items;
//Resources
// http://stackoverflow.com/questions/442404/retrieve-the-position-x-y-of-an-html-element