我有一个包含标题和其他两个框的框。标题的顶部边距为负,以便在框外呈现。在除 Firefox 之外的所有浏览器中,标题都会正确拉出其同级框,但在 Firefox 中,这些框保持在原位。
如果我从盒子中取出浮子,那么它们确实会向上移动。除了给盒子加上负的 margin-top 之外,还有其他解决办法吗?
div {
background: red;
padding: 2rem;
margin-top: 8rem;
box-sizing: border-box;
}
div:after {
display: table;
content: "";
clear: both;
}
div div {
background: green;
margin: 0 0 2rem;
width: 45%;
float: left; /* Remove this and float: right below and it works in FF */
}
div div + div {
float: right;
}
h2 {
margin-top: -8rem;
}
<div>
<h2>
Hello
</h2>
<div>
These boxes also render outside the red one.
</div>
<div>
In every browser except Firefox.
</div>
</div>
最佳答案
您可以将 float 的盒子包裹在非 float 的容器中。 (注意:我为每个 div 提供了自己的类,只是为了更清楚地明确哪些样式应用于哪个 div。)
.d1 {background:red; padding:2rem; margin-top:8rem; box-sizing:border-box;}
.d1:after {display:table; content:""; clear:both;}
.d3 {float:left; background:green; padding:2rem; box-sizing:border-box; width:45%;}
.d3 + .d3 {float:right;}
h2 {margin-top:-8rem;}
<div class="d1">
<h2>Hello</h2>
<div class="d2">
<div class="d3">These boxes render outside the red one.</div>
<div class="d3">In every browser.</div>
</div>
</div>
关于html - 负边距不会拉起 Firefox 中 float 的同级,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40886181/