这很奇怪。我试图在右浮动的 div 旁边设置一个固定宽度的 div,我不想重新排序 div(因为这是分布式主题)。因此,我在固定 div 上使用负 margin-right 进行游戏,结果在我看来很奇怪:如果它是 -4px 或更小,那么 float 会移到一边;否则,它保持在下方。
玩live demo with code at jsbin ,它有这个:
<style>
.container {
width: 200px;
height: 200px;
}
.box {
width: 100px;
height: 100px;
}
.one {
margin-right: -4px; /* If <= -4, .two box shifts up */
display: inline-block;
}
.two {
float: right;
}
</style>
<div class="container">
<div class="box one"></div>
<div class="box two"></div>
</div>
有人能解释一下其中的奥秘吗?在这种情况下,数字 -4 有什么特别之处?
最佳答案
4px
正好是那个font-size
的“空格”的宽度。
如果您将#container
的font-size
更改为32px
,it breaks .
解决此问题的明智方法包括:
- Remove
margin-right: -4px
and then remove the whitespace between thediv
s in the HTML . - 不要使用
display: inline-block
。相反,float: left
the leftdiv
, andfloat: right
the rightdiv
.- 如果你担心 it breaking当您在容器上没有固定的
height
时,您必须清除 float 。在容器上使用overflow: hidden
,或者使用clearfix . - With
overflow: hidden
(使用这个除非你有 specific problems ) - With clearfix
- 如果你担心 it breaking当您在容器上没有固定的
关于css - 修复了带有负边距和移动 float 的内联 block div : what's special about -4px?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6614999/