我有一个主 div(页面),其中有另一个内部 div(中央)。我为两个 div 应用了 CSS。我在 CSS 中分别为两个 div 提供了 margin-top 属性,但内部 div 的 margin-top 也应用于外部 div。我该如何解决这个问题?
CSS:
#page
{
position: relative;
margin: auto;
margin-top: 40px;
margin-left: auto;
background-color: #b3dced;
height: 900px;
width: 900px;
border-radius: 10px;
}
.central
{
position: relative;
margin: auto;
margin-top: 80px;
background-color: blue;
height: 500px;
width: 500px;
border: 2px solid green;
border-radius: 10px;
}
<body>
<div id="page">
<div class="central">
<table>
<tr>
<td>name</td>
<td><input type="text" /></td>
</tr>
<tr>
<td>name</td>
<td><input type="text" /></td>
</tr>
<tr>
<td>name</td>
<td><input type="text" /></td>
</tr>
</table>
</div>
</div>
</body>
最佳答案
该问题被称为 Margin Collapsing
.
When the vertical margins of two elements are touching, only the margin of the element with the largest margin value will be honored, while the margin of the element with the smaller margin value will be collapsed to zero.
您可以在子元素上使用 padding
或 top
来避免这种情况。或者在父级上添加一点填充。像这样:
#page {
padding-top:1px;
}
检查这个http://jsfiddle.net/269Pw/6/ .
关于这个Article您可以找到有关此问题的更多信息以及解决该问题的多种方法。
关于css - 无法正确对齐嵌套 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21537254/