【问题标题】:How to clear a block element after floated divs without extra markup?如何在没有额外标记的浮动 div 后清除块元素?
【发布时间】:2023-03-08 15:16:01
【问题描述】:

我有两个浮动 div,在它们之后我有一个带有 margin-top 的块元素。不幸的是,margin-top 因为浮动而不起作用。是否可以在代码中添加margin-top 而无需额外标记?

我尝试使用 :after,但没有帮助。

div {
    background-color: red;
}
#left {
    float: left;
    height: 100px;
    background-color: yellow;
}
#right {
    float: right;
    height: 100px;
    background-color: yellow;
}
#content {
    margin-top: 50px;
    height: 100px;
    clear: both;
}

#content:before {
    clear: both;
    content: "";
    display: table;
}

<div id="left">left</div>
<div id="right">left</div>
<div id="content">left</div>

div {
    background-color: red;
}
#left {
    float: left;
    height: 100px;
    background-color: yellow;
}
#right {
    float: right;
    height: 100px;
    background-color: yellow;
}
#content {
    margin-top: 50px;
    height: 100px;
    clear: both;
}

#content:before {
    clear: both;
    content: "";
    display: table;
}
<div id="left">left</div>
<div id="right">left</div>
<div id="content">left</div>

【问题讨论】:

    标签: html css css-float margin


    【解决方案1】:

    哦,那些折叠的边距......

    如果您将最后一个 div 的上边距更改为前两个 div 的下边距,它会按预期工作。

    div {
      background-color: red;
    }
    #left {
      float: left;
      height: 100px;
      background-color: yellow;
      margin-bottom: 50px;
    }
    #right {
      float: right;
      height: 100px;
      background-color: yellow;
      margin-bottom: 50px;
    }
    #content {
      height: 100px;
      clear: both;
    }
    <div id="left">left</div>
    <div id="right">right</div>
    <div id="content">content</div>

    【讨论】:

    • 是的,这是真的,但为什么在#content div 上不起作用?
    • @user1452062 由于clear 的工作方式:它将#content 的上边距设置为这样一个值,即div 恰好位于浮动元素的下方。即使将margin-top 设置为一个非常大的值,比如1000px,也无济于事;它只是没有使用。
    • @user1452062 作为 clear 导致它的证据,请尝试从您自己的 sn-p 中删除 clear。然后你会看到边距确实被应用了。除了它也适用于两个浮动 div,所以这不是一个好的解决方案!
    猜你喜欢
    • 2023-03-21
    • 2015-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多