css - 无法正确对齐嵌套 div

标签 css html

我有一个主 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;
}

Align the divs fiddle link

<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.

您可以在子元素上使用 paddingtop 来避免这种情况。或者在父级上添加一点填充。像这样:

#page {
  padding-top:1px;
}

检查这个http://jsfiddle.net/269Pw/6/ .

关于这个Article您可以找到有关此问题的更多信息以及解决该问题的多种方法。

关于css - 无法正确对齐嵌套 div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21537254/

相关文章:

css - 指示不应在保存时编译 LESS 文件

html - 和空间有什么区别?

javascript - jQuery 找不到自定义标签

html - 文本未包装在 flexbox 中

javascript - 如何以编程方式指定要在浏览器中打印的页面范围(使用 javascript 或 css)

jquery - 计时器 - 使用 jquery 函数在 2 秒内显示 0 到贬值

css - <main> 元素在 Internet Explorer 11 中不起作用

html - Ruby on Rails SSL_connect 错误

javascript - jQuery 弹出窗口与 Asp.Net MVC 不能很好地配合

html - 使用 HTML5/CSS3 更改工具提示位置