CSS Float left and align right


We often have situations where we have elements sitting side by side in the design of a website and CSS has provided us with an easy way to achieve this using the float attribute. A common example might be the navigation on a website.


<ul class="primary-nav-menu">
<li><a href="/" title="Home" >Home<a><li>
<li><a href="/page-1" title="Page 1" >Page 1<a><li>
<li><a href="/page-2" title="Page 2" >Page 2<a><li>
<li><a href="/page-3" title="Page 3" >Page 3<a><li>
</ul>
Navigation HTML snippet

.primary-nav-menu li {
float: left;
}
CSS to display the nav items in a row

Now what if we wanted the nav items to sit on the right hand side of the page? Well we could float the whole thing to the right, applying “float: right;” to the ul element but that may have further implications with regards to the surrounding elements. We could change the CSS we applied to the list items to float them right instead of left, however this will reverse the order of the list items.

So onto the solution. With all current browsers providing support for the inline-block property, we can now use this to solve our problem instead of having to float the elements. Applying “display: inline-block;” will place all the elements in a row in the order provided. The group of block level elements are now treated as if they are inline elements so to get them to align to the right, all we need to do is apply the CSS attribute “text-align: right;”


.primary-nav-menu {
text-align: right;
}

.primary-nav-menu li {
display: inline-block;
*display: inline; /* Fix for IE */
zoom: 1; /* Fix for IE */
}

CSS to display the nav items in a row

Leave a Reply

Your email address will not be published. Required fields are marked *