What Does This CSS Code Do ?

Asked

Viewed 212 times

7

This is looking at some snippets of code on the Internet for a deeper learning of CSS, and I saw this code contained in a menu and I would like to know its functionality.

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

3 answers

7


This rule will create a special element (called pseudo element) before and after those who possess the class .nav. In this particular case, it appears to be a type of clearfix, placing two spaces between the element and the :after the property is applied clear:both.

Probably because the items in this menu use the property float who has an annoying behavior to work with and can be seen in that Mozilla article. This technique of floating elements has been decreasing, at least that’s what I follow. As an alternative display:inline-block is used and most recently the flexbox, but the latter still has limited support.

CLEARLESS:

nav { border: 2px solid red }
a { float: left; border: 2px solid blue }
<nav>
  <a href='#'>Link</a>
  <a href='#'>Link</a>
  <a href='#'>Link</a>
  <a href='#'>Link</a>
</nav>

CLEARFIX:

nav { border: 2px solid red }
a { float: left; border: 2px solid blue }

nav::after,
nav::before {
  content: ' ';
  display: table
}

nav::after {
  clear: both
}
<nav>
  <a href='#'>Link</a>
  <a href='#'>Link</a>
  <a href='#'>Link</a>
  <a href='#'>Link</a>
</nav>

  • 1

    This answer is very good, I believe it was lacking to explain why the display: table generating an anonymous cell and applying block formatting thus preventing the top and bottom edges from combining into one (margin Collapse) http://nicolasgallagher.com/micro-clearfix-hack/

4

Basically, it will before and after (before/after) add a space and display in table format (display: table;).

  • I did not understand what would be displayed as table.

  • Usually this serves to clean the float:left, if I’m not mistaken

2

This type of CSS formatting is often used in ready-made CSS Frameworks icons, for example bootstrap.

.glyphicon-asterisk:before {
  content: "\2a";
}
.glyphicon-plus:before {
  content: "\2b";
}

This code for example exposes on the screen an asterisk in the form of an icon/image and the other exposes another element. When connected to Bootstrap (http://getbootstrap.com.br/)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.