2

I was shown the following CSS for horizontally aligning elements within a div

<ul id="nav">
    <li><a href="#">HOME</a></li>
    <li><a href="#">ABOUT</a></li>
    <li><a href="#">BASIC SERVICES</a></li>
    <li><a href="#">OUR STAFF</a></li>
    <li><a href="#">CONTACT US</a></li>
</ul>

#nav {
text-align: justify;
min-width: 500px;
}

#nav:after {
content: '';
display: inline-block;
width: 100%;
}

#nav li {
display: inline-block;
} 

http://jsfiddle.net/danield770/9hh86/

What is the purpose of the content: ' '? I understand it adds on a space to the end of the 'nav' div, but why does this help align the list elements?

rohaldb
  • 589
  • 7
  • 24

1 Answers1

3

The purpose of the content: '' declaration, specifically, is so that the :after pseudo-element can be rendered. Without it, there won't be a pseudo-element, and it'd be as though the :after rule were missing altogether.

The space at the end of the element that you refer to is a 100%-width inline-block. This causes it to wrap to the next line after the list elements since there isn't enough space to fit it on the same line. This wrapping forces the list elements in the line before it to justify because of the text-align: justify declaration.

You can see where exactly the :after is being rendered by adding an outline to it like so:

#nav {
  text-align: justify;
  min-width: 500px;
  padding: 0;
}

#nav:after {
  content: '';
  display: inline-block;
  width: 100%;
  outline: 1px solid;
}

#nav li {
  display: inline-block;
}
<ul id="nav">
    <li><a href="#">HOME</a></li>
    <li><a href="#">ABOUT</a></li>
    <li><a href="#">BASIC SERVICES</a></li>
    <li><a href="#">OUR STAFF</a></li>
    <li><a href="#">CONTACT US</a></li>
</ul>
BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • This same explanation is given in the comments on the answer where the fiddle originates: http://stackoverflow.com/questions/5060923/how-to-stretch-html-css-horizontal-navigation-items-evenly-and-fully-across-a/17951253#comment28986486_17951253 – BoltClock Dec 02 '15 at 05:31
  • Thank you very much. I also added the following to my css: * { margin: 0px } So that my images would fit my page nicely, however this causes the end element of the navigation to sit very closely to the right hand side of the page. Is there a simple way to fix it? – rohaldb Dec 02 '15 at 05:59