CSS Pseudo Menu Items
Posted: Tue, Mar 8 03:21 PM (PST)The usually when you need to do inline menu really fast, the most of designers use this method
<ul> <li><a href="#">Item One</a></li> <li>|</li> <li><a href="#">Item Two</a></li> <li>|</li> <li><a href="#">Item Three</a></li> <li>|</li> <li><a href="#">Item Four</a></li> </ul>
with the end result looking like the following
Item One | Item Two | Item Three | Item Four
However I'm sure you will all agree that this is far from ideal. In that example alone we're sticking in an extra three list items that contribute absolutely nothing other than website and as we're all told, we should be separating content from website with the use of CSS.
So where do the pseudo elements come in? Well, if we strip out the three redundant list items our code will now look like the following
<ul> <li><a href="#">Item One</a></li> <li><a href="#">Item Two</a></li> <li><a href="#">Item Three</a></li> <li><a href="#">Item Four</a></li> </ul>
And CSS code
ul li { list-style:none; display:inline; float:left; margin:0 5px 0 0; }
ul li:after { content:"|"; margin:0 0 0 5px; }
ul li:last-child:after { content:""; }
By applying the following CSS to our code our example menu item now looks exactly like what we were aiming for
Item One | Item Two | Item Three | Item Four
Lets now breakdown the CSS and see what each part plays in order to achieve our final result?
The first section of CSS will set out a list like normal, removing all list styles, making the menu display inline, floating every list item left to make them all fall in line with each other and finally adding a margin to the right to add more spacing to the list items.
In the next section we make use of the :after pseudo element on the list elements. We use the content property to add the vertical line after each menu option and adding a margin to the left to make sure that the vertical line is evenly positioned between it's surrounding li elements.
Within the final section of our CSS code we make use of two final pseudo elements; :last-child and :after. The :last-child pseudo element will find the last element within any parent element. In the second section of our CSS we used the content property to add a vertical line after each li but because we are targeting the last element we can remove the vertical line by adding in another content property and leaving it blank and the :after element tells the browser which side of the element we are targeting.
Tags: