Satya Prakash
Satya Prakash

Reputation: 3502

Why this selector:after Piece of CSS Code is Used?

I got this piece of code from here:

div.grid:after {
  clear: both;
  content: ".";
  display: block;
  height: 0;
  visibility: hidden;
}

Even when I delete, nothing happens. So, could not make sense.

I see many tricks based on :before and :after are in use these day. I thought to understand this, so asked.

Upvotes: 0

Views: 89

Answers (4)

Mr. Alien
Mr. Alien

Reputation: 157334

If you are asking for the piece of code you shared, it clears the floating elements, say for example you have this

Demo (Without :after pseudo to self clear parent)

Demo 2 (Using :after with the properties to clear floating elements)


If you are asking specifically about :after than it's just like a virtual element. It just adds content after the element. You also have :before which will add content before instead. The pseudo generated content is inline by default.

This feature is really handy say when you want to add some content before or after the element, now you will say how is this really useful in real world, than consider this as 2 elements which you can just make act like a div by making it a block level like

div.class_name:before, 
div.class_name:after {
   display: block;
} 

Will just save you 2 elements in DOM, I would like to share few links where I've used this feature to cut down HTML...

Answer Here - Demo

Answer Here - Demo

Answer Here - Demo


MDN Reference | Support

Upvotes: 1

user2021917
user2021917

Reputation:

This “clearfix” generates pseudo-elements and sets their display to table. This creates an anonymous table-cell and a new block formatting context that means the :before pseudo-element prevents top-margin collapse. The :after pseudo-element is used to clear the floats. As a result, there is no need to hide any generated content and the total amount of code needed is reduced.

Including the :before selector is not necessary to clear the floats, but it prevents top-margins from collapsing in modern browsers. This has two benefits:

1.It ensures visual consistency with other float containment techniques that create a new block formatting context, e.g., overflow:hidden

2.It ensures visual consistency with IE 6/7 when zoom:1 is applied.

Upvotes: 1

Anenth
Anenth

Reputation: 702

This code is used for clearing the floats :before and :after can serve many purpose and its really usefull

for example if you want to add $ to the currency

.currency:before{
   content :'$';
}

this will add $ to all the classes currency, so it saves lots of time here is the jsfiddle

Checkout this resouses link

Upvotes: 0

suff trek
suff trek

Reputation: 39777

:after in conjunction with content can be used to add content after elements. Try this:

span:after {
    content: "world"
}

<span>Hello </span>

http://jsfiddle.net/d3M99/

Upvotes: 0

Related Questions