Skip to content Skip to sidebar Skip to footer

How The Block Element Works Inside A Floated Div?

This is a continuation of the following question: CSS Float - The content stays in the default stack position When I am adding a block element(p element) inside box1, (which comes

Solution 1:

There isn't enough room for the text in the p to start a new line there, so it starts only at the right edge of the float, giving the appearance of a gap underneath the float. If you give the p a slightly bigger top margin, there will be enough room for the second line of text to start directly underneath the float:

p {
    margin-top: 1.2em;
    border: 1px solid #000;
}

You can also increase the line-height as mentioned by others; this will cause the first line to be tall enough for the second line to have room to start underneath the float.

The reason why the boundaries of the p element don't shift completely out of the float is because the p element behaves exactly like .box1, since neither of them are floating. The text wraps in the same way I've described in my previous answer.


The reason why it behaves differently when you add display: inline-block, float: left or overflow: hidden is given in the comments on my previous answer:

overflow: hidden causes the box to generate a block-formatting context, which makes it immune to surrounding floats. That causes the entire box to shift outside of the float and sit right next to it instead.

(Technically, display: inline-block also causes the p element to act like an inline element itself, in other words, it is rendered inline just like the first sentence in .box1, but this has the same effect.)

When neither .box1 nor p are generating block formatting contexts, they are both participating in the same context, which is actually that of the root element. This is what causes them to interact with the float the way you are observing.

Block formatting contexts are a very complicated and broad topic that I would rather not get into myself, but the answer to this question has a nice visual explanation on how they work and how elements interact with one another around them in various scenarios.

Solution 2:

I would assume this is to do with the line height.

p {
    border: 1px solid #000;
    line-height:1.5;
  }

This works :)

Solution 3:

add overflow: hidden; in box1 class.Try this once.

Post a Comment for "How The Block Element Works Inside A Floated Div?"