31

I got http://jsfiddle.net/8p2Wx/2/ from a previous question I asked and I see these lines:

.cf:before,
.cf:after {
    content:"";
    display:table;
}

.cf:after {
    clear:both;
}

If I take away content:"", it ruins the effect, and I don't understand why it's necessary.

Why is it needed to add an empty content to :after and :before pseudo-elements?

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
qwertymk
  • 34,200
  • 28
  • 121
  • 184

3 Answers3

31

You cannot style generated content without defining what that content should be. If you don’t really need any content, just an extra “invisible element” to style, you can set it to the empty string (content: '') and just style that.

It’s easy to confirm this yourself: http://jsfiddle.net/mathias/YRm5V/

By the way, the snippet you posted is the micro clearfix hack, which is explained here: http://nicolasgallagher.com/micro-clearfix-hack/

As for your second question, you’ll need an HTML5 shiv (small piece of JavaScript) to make <nav> stylable in some older browsers.

Mathias Bynens
  • 144,855
  • 52
  • 216
  • 248
  • Doesn't the nav has a `ul` in it already? How is it empty? – qwertymk Mar 07 '12 at 10:49
  • 1
    Generated content gives you an extra invisible element inside of the real element. E.g. using `ul:after` in CSS and setting its `content` property to something will append a new element to the `
      ` that is invisible in the DOM, but stylable through CSS.
    – Mathias Bynens Mar 07 '12 at 10:52
  • This answer doesn't explain anything. – Robo Robok Jul 30 '20 at 20:10
4

As the CSS spec. states, :after and :before pseudo elements are not generated if prop. content isn't set to a value other than 'normal' and 'none': http://www.w3.org/TR/CSS2/generate.html#content

content initial value is 'normal' and 'normal' computes to 'none' for the :before and :after pseudo-elements.

Josh Lee
  • 171,072
  • 38
  • 269
  • 275
luissquall
  • 1,740
  • 19
  • 14
0

CSS has a property called content. It can only be used with the pseudo elements :after and :before. It is written like a pseudo selector (with the colon), but it's called a pseudo element because it's not actually selecting anything that exists on the page but adding something new to the page

see this for better explanation :

  1. Css Content 1
  2. Css Content 2

and the nav element is :

One of the new elements for HTML 5 is the element which allows you to group together links, resulting in more semantic markup and extra structure which may help screenreaders. In this article I’ll discuss how and where to use it as well as some reservations I have with the specifications definition.

  1. Html5 TAGS
Jack
  • 1,442
  • 12
  • 20