所以我有 2 个 div。一个是页面上向左浮动的侧边栏。然后我在它的右边有一个主体 div。在我将侧边栏更改为 float 之前,我可以毫无问题地为主 div 设置边距和填充。但是,如果侧边栏设置为 float ,则主 div 上的样式将停止生效。这是 CSS:
#columns {
background: #141;
#main {
margin-left: 17em;
padding: 1em;
padding-left: 3em;
background: blue;
}
#side {
float: left;
padding: 1em 2em;
width: 13em;
background: #141;
height: 100vh;
margin-right: 2em;
ul {
padding: 0;
li {
list-style: none;
a {
color: #bfb;
font-size: small;
}
}
}
我猜这是我不知道的 float 的一些属性。有什么想法吗?
最佳答案
为什么会这样?
我们来看看a simple explanation of float
:
The float CSS property specifies that an element should be taken from the normal flow and placed along the left or right side of its container, where text and inline elements will wrap around it. A floating element is one where the computed value of float is not none.
让我们看看将主 div 设置为内联的效果:
body {
margin: 0;
}
#main {
background: blue;
display: inline;
padding: 10px;
margin: 0 10px;
}
#side {
float: left;
width: 13em;
background: rgba(0, 0, 0, 0.5);
height: 300px;
}
<div id="side">
</div>
<div id="main">
</div>
结果
内联 div 包裹在它周围,棒极了。
现在让我们把那个 div 变回 display: block
,默认值:
body {
margin: 0;
}
#main {
background: blue;
padding: 10px;
margin: 0 10px;
width: 100px;
height: 100px;
}
#side {
float: left;
width: 13em;
background: rgba(0, 0, 0, 0.5);
height: 300px;
}
<div id="side">
</div>
<div id="main">
</div>
结果
block div 位于 float div 下方!为什么!?让我们再看看那个解释:
The float CSS property specifies that an element should be taken from the normal flow and placed along the left or right side of its container, where text and inline elements will wrap around it. A floating element is one where the computed value of float is not none.
解释
float 的 div 从正常文档流中取出, block div 忽略它。
如何防止这种行为并仍然使用 float ?
很简单,将block div也从正常流程中取出来;应用 float: left
body {
margin: 0;
}
#main {
background: blue;
padding: 10px;
margin: 0 10px;
width: 100px;
height: 100px;
float: left;
}
#side {
float: left;
width: 13em;
background: rgba(0, 0, 0, 0.5);
height: 300px;
}
<div id="side">
</div>
<div id="main">
</div>
关于html - 当它旁边的 div float 时,div 的填充不起作用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26520108/