Float and block level elements

后端 未结 2 757
别跟我提以往
别跟我提以往 2021-01-02 14:48

Can anyone tell me why do the block level elements given float property does behave oddly? I want to understand what actually happens to an element[block or inline] when we

相关标签:
2条回答
  • 2021-01-02 15:14

    When you float an element it takes it out of the normal flow. If you inspect it's parent without any other siblings, the parent element will not have a height. The floated element actually punches through the bottom of its parent.

    Floating an element also makes its width collapse to the width of its content (if any). That means, if it has no content, it'll be 0 width. So, if you want it to have a certain width, you have to set that.

    If you want the parent to contain it, you'll either need a sibling element to clear the float with "clear: both" or you'll need to do something like bootstrap does with ".clearfix" (Understanding Bootstrap's clearfix class)

    Depending on how you want the floated element’s siblings to interact with it, you may also need to float them.

    0 讨论(0)
  • 2021-01-02 15:25

    It is because the original intended purpose of floats was not to put block elements side by side, but to reproduce the traditional typographical effect of wrapping text around images and boxouts as seen in this diagram from the CSS 2 spec.

    There are various workarounds, but you'd probably be better off with display: inline-block, flexbox or CSS grids if you want side-by-side blocks.

    0 讨论(0)
提交回复
热议问题