-2

I have a div which contains some thumbnails and contain few images which uses floats. But using floats the background image/color would shrink since the images float so there's no contents for the background image/color unless I fix the length and width of background image/color.

I then found online that by using this code my problem is solved.

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

.cf:after {
    clear:both;
}

I know how does clear:both works but I am not sure how did the content: " "; display: table; fixed the problem. I kind of guessed it but can someone simply explain to me nicely?

Thanks in advance.

I added two images in case my bad explanation is hard to understand.

enter image description here

enter image description here

Edit. Thanks people. Didn't know this is called clearfix no wonder I kept on typing things like :after :before Pseudo-elements for floats or similar and I couldn't find what I need. But I don't think this question is much of a duplex because what I wanted to ask is how the clearfix works instead of clearfix vs floats.

Thanks Prashant for the link~

WXR
  • 481
  • 1
  • 7
  • 18

1 Answers1

0

The real reason behind adding content: " "; display: table; to pseudo-elements(:before ,:after ) is that --->

:before pseudo-element Creates an anonymous table-cell and a new block formatting context. Although this is not neccessary,This prevents top-margin collapse. The use of table rather than block is necessary to contain the top-margins of child elements.

:after pseudo-element is used to clear the floats.( clear: both; )

Source: http://nicolasgallagher.com/micro-clearfix-hack/

Prashant
  • 446
  • 1
  • 4
  • 15