【发布时间】:2019-12-13 22:16:20
【问题描述】:
我遇到了这样的布局问题:
.wrapper {
clear: both;
background-color: #ccc;
}
.wrapper+.wrapper {
margin-top: 50px;
}
.side,
.main {
height: 100px;
padding: 10px;
box-sizing: border-box;
margin-top: 20px;
}
.box {
padding: 10px;
}
.top {
background: yellow;
}
.side {
width: 100px;
float: left;
background: lightblue;
}
.main {
margin-left: 100px;
background: lightgreen;
}
<div class="wrapper">
<div class="top"></div>
<div class="side">side</div>
<div class="main">main</div>
</div>
<div class="wrapper">
<div class="top">
<div class="box">top</div>
</div>
<div class="side">side</div>
<div class="main">main</div>
</div>
.main 和 .side 元素需要对齐。正如您在上面的 sn-p 中看到的,一切都很好,除非 .top 元素没有高度,在这种情况下 margin-top 规则会导致它们倾斜。以下所有“修复”问题,但每个都有一个缺点:
- 为
.wrapper添加边框(我可能可以使用透明边框,但我真的不喜欢这样,因为它感觉像一个肮脏的黑客,我宁愿不添加边框。出于某种原因边框需要有至少 1px 的宽度,否则这不起作用)
.wrapper {
clear: both;
background-color: #ccc;
border: 1px solid #000;
}
.wrapper+.wrapper {
margin-top: 50px;
}
.side,
.main {
height: 100px;
padding: 10px;
box-sizing: border-box;
margin-top: 20px;
}
.box {
padding: 10px;
}
.top {
background: yellow;
}
.side {
width: 100px;
float: left;
background: lightblue;
}
.main {
margin-left: 100px;
background: lightgreen;
}
<div class="wrapper">
<div class="top"></div>
<div class="side">side</div>
<div class="main">main</div>
</div>
- 将
overflow: hidden添加到.wrapper(这会隐藏某些元素的一部分并导致其他元素落入错误的位置) - 将
overflow: auto添加到.wrapper(这在某些情况下会添加滚动条)
最后两个在我的 sn-p 中并不明显,但在现实世界的应用程序中,它们会导致问题,如 here 所述。
我强烈怀疑该问题与Why doesn't the height of a container element increase if it contains floated elements? 和CSS container doesn't stretch to accommodate floats 有关,但我已经尝试了许多这些建议,但似乎没有一个可以完全解决问题 - 可能是因为我的一个 div 是浮动的,而另一个是不是。
由于这是一个大型应用程序的一部分,我不想彻底改变布局,只要有一些 CSS 将保持 .main 和 .side 对齐,而不管这些元素之前的内容如何。
【问题讨论】:
-
为什么不使用 flexbox 呢?甚至 inline-block 都可以完成这项工作
-
@TemaniAfif - 请在下面查看我对符号链接的回答的回复。感谢您的建议,我已经使用了 flex 并且喜欢它——但不幸的是,这不是一个选择。正如我在问题中提到的,我想在不更改布局的情况下解决问题。
-
顺便说一句,问题与页边距折叠有关,其中父页边距与 first 流入子项一起折叠(在您的情况下,这是第二个,因为第一个已出流量)
-
我对此有一种感觉 - 我只是对如何在布局的上下文中解决它感到困惑。
-
并且您希望第一个案例中的页边距顶部展开?你想一直看到灰色吗?