rohaldb
rohaldb

Reputation: 588

What is the purpose of adding content:' ' in the following code?

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?

Upvotes: 2

Views: 92

Answers (1)

BoltClock
BoltClock

Reputation: 723739

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>

Upvotes: 3

Related Questions