css - 下一个 div 的边距不适用于 float 在 div 上方

标签 css css-float

我有一个并排的 50% div。在我下面有一个内容 div,我在其中应用了 margin-top 60px。这个 margin 是行不通的。

<div class="sbs50">
    Left Side
</div>
<div class="sbs50">
    Right Side
</div>
<div class="content-section">
    Content Section
</div>

CSS

.sbs50
{
    float: left;
    width: 50%;
}

.content-section
{
    margin-top: 60px;
    border: 1px solid green;
}

我尝试添加以下内容但不起作用

.sbs50:after 
{
    content:'';
    display:block;
    clear: both;
}

如何解决边距不起作用的问题?

这是我的 fiddle

最佳答案

只需将边距添加到 sbs50 类的底部并清除 .content-section 类的 float 。像这样:

.sbs50 {
    float: left;
    width: 50%;
    margin-bottom:50px;
}
.content-section {
    border: 1px solid green;
    display:block;
    clear: both;
    float:none;
    background:#ccc;
}

See fiddle

替代方案:

使用典型的清除方法,基本上是添加一个清除每个 float 的 div。所以你的 HTML 看起来像这样:

<div class="sbs50">Left Side</div>
<div class="sbs50">Right Side</div>
<div class="clearfix"></div><!-- added div -->
<div class="content-section">Content Section</div>

你的 CSS 是这样的:

.sbs50 {
    float: left;
    width: 50%;
}
.clearfix {
    display:block;
    clear: both;
    float:none;
}
.content-section {
    border: 1px solid green;
    margin-top:200px;
    background:#ccc;
}

See fiddle for this example

这是一种更常见的方法,因为您只需清除元素,然后根据需要设置后续元素的样式,但您可以使用这些方法中的任何一种,它们的效果都一样好

关于css - 下一个 div 的边距不适用于 float 在 div 上方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25799419/

相关文章:

html - CSS如何使DIV边框在宽度上动态变化

Css float 问题

html - float 框旁边列表的左边距

javascript - 在悬停在另一个 div 上时显示一个 div 会导致对服务器的多个请求和闪烁

css - 为什么在父项上应用 CSS-Filter 会破坏子项定位?

html - 在 gwt 应用程序中嵌入模板

html - Outlook 2010 无法识别 HTML 表格

html - float 的 CSS 框

列表的 css float 在 <IE7 中不起作用

CSS 高级 float /网格布局