Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need an empty `content` property on an ::after pseudo-element? [duplicate]

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?

like image 594
qwertymk Avatar asked Mar 07 '12 10:03

qwertymk


People also ask

Why do pseudo-elements need content?

Pseudo classes exist for every markup element. They are invisible by default, because they are initialized with no content property. You CANNOT set the content property for pseudo classes with HTML markup. ∴ Therefore, pseudo-elements' content property must be declared with CSS declarations, in order to be displayed.

When would you use the :: before or :: after pseudo-element in your CSS?

Special welcome offer: get $100 of free credit. CSS ::before and ::after pseudo-elements allow you to insert “content” before and after any non-replaced element (e.g. they work on a <div> but not an <input> ). This effectively allows you to show something on a web page that might not be present in the HTML content.

What does :: After mean in HTML?

::after (:after) In CSS, ::after creates a pseudo-element that is the last child of the selected element. It is often used to add cosmetic content to an element with the content property. It is inline by default.

What is :: before and :: after?

Definition and UsageThe ::before selector inserts something before the content of each selected element(s). Use the content property to specify the content to insert. Use the ::after selector to insert something after the content.


2 Answers

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.

like image 84
Mathias Bynens Avatar answered Sep 28 '22 05:09

Mathias Bynens


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.

like image 26
luissquall Avatar answered Sep 28 '22 04:09

luissquall