-2

In this example, why does container need to have the pseudo-element after and before with content: '' and display: table to show the gray background? Shouldn't container automatically expand to fit both of its children and then fill out the negative space with the gray background without the pseudo-elements already?

stackjlei
  • 9,485
  • 18
  • 65
  • 113

1 Answers1

-1

This is called a 'clearfix', when a container has all of his the childs floating, you have to use a clearfix on it. I put a black background in the container:

With clearfix: https://codepen.io/anon/pen/GvoEjx

Without clearfix: https://codepen.io/anon/pen/NvxgRe

https://css-tricks.com/snippets/css/clear-fix/

.container:before,
.container:after {
  content: "";
  display: table;
  clear: both;
}
jvitoroc
  • 380
  • 1
  • 4
  • 16
  • 1
    Additionally, `display: flow-root` is now an option in some browsers, for which the explanation of how it differs from clearfix is quite technical. – jhpratt Jul 30 '17 at 02:02
  • clear:fix doesn't allow elements to be floating above it, but in this situation how does it affect whether the container element get a background or not? – stackjlei Jul 30 '17 at 02:49
  • Also for that example, why do you need it in the `before`? Don't you just need it for the `after`? – stackjlei Jul 30 '17 at 02:50
  • 1
    The element get a background in any case, but without clearfix, The container cant get The height of The content, in other words, we cant see The background @stackjlei – jvitoroc Jul 30 '17 at 03:12
  • You dont need to know how it works, but what it does – jvitoroc Jul 30 '17 at 03:14
  • 1
    You might as well not bother answering the question in that case. – BoltClock Jul 30 '17 at 04:35
  • Omg, just google clearfix – jvitoroc Jul 30 '17 at 15:39