What does this CSS code do?

8

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 would like to know what the functionality of it.

.nav:before,
.nav:after {
    content: " ";
    display: table;
}
    
asked by anonymous 16.03.2016 / 18:42

3 answers

5

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

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

NO CLEARFIX:

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>

WITH 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>
16.03.2016 / 21:05
4

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

    
16.03.2016 / 18:47
2

This type of CSS formatting is often used in already-ready FrameWorks CSS icons, for example the bootstrap.

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

This code, for example, exposes an asterisk in the form of an icon / image on the screen and the other exposes another element. When connected to BootStrap ( link )

    
16.03.2016 / 20:14