Why can't I clear float when using BFC feature on body?

不羁的心 提交于 2021-02-08 06:13:14

问题


On other tags, using BFC can clear the float, why the body is not available. As expected, add overflow: hidden on the body to form a BFC, which can achieve the effect of clearing the float, but this is not the case?

div.f {
  float: left;
  width: 100px;
  height: 100px;
  background: red;
  margin-right: 1px;
}

body {
  overflow: hidden;
  border: 1px dashed skyblue;
}

.p {
  overflow: hidden;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <!-- <div class="p">
        <div class="f"></div>
        <div class="f"></div>
    </div> -->

    <div class="f"></div>
    <div class="f"></div>
</body>

</html>

回答1:


because overflow has a special behavior when applied to body element and it get propagated to html element instead. You need to add overflow:auto to html to avoid this:

div.f {
  float: left;
  width: 100px;
  height: 100px;
  background: red;
  margin-right: 1px;
}

body {
  overflow: hidden;
  border: 1px dashed skyblue;
}

html {
  overflow: auto;
}
<div class="f"></div>
<div class="f"></div>

UAs must apply the overflow-* values set on the root element to the viewport. However, when the root element is an [HTML] html element (including XML syntax for HTML) whose overflow value is visible (in both axes), and that element has a body element as a child, user agents must instead apply the overflow-* values of the first such child element to the viewport. The element from which the value is propagated must then have a used overflow value of visible. ref

So you body element will have again overflow:visible after the propagation




回答2:


To have it working on the body, you can use display:flow-root, I believe this is have to do with how the width of the content affects the body display/render, and by adding display:flow-root it will clear floated tag inside it.

div.f {
  float: left;
  width: 100px;
  height: 100px;
  background: red;
  margin-right: 1px;
}

body {
  display: flow-root;
  border: 1px dashed skyblue;
}

.p {
  overflow: hidden;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <!--<div class="p">
        <div class="f">AAAA</div>
        <div class="">test</div>-->
    </div>

    <div class="f"></div>
    <div class="f"></div>
</body>

</html>


来源:https://stackoverflow.com/questions/61672990/why-cant-i-clear-float-when-using-bfc-feature-on-body

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!