【问题标题】:margin-top not working as expected without padding on surrounding div没有在周围 div 上填充的情况下,margin-top 无法按预期工作
【发布时间】:2013-04-13 10:09:44
【问题描述】:

我在容器 div 内的 div 中有一个图像。当我将 margin-top 应用到图像时,margin 被应用到容器 div 的外部(将容器推)相对于 body 向下。

我可以通过在另一个 div 上应用填充来“修复”这个问题……但我宁愿在图像上留出边距。如果我在另一个(不是容器)div 上应用 1px 填充,那么 margin-top 在将图像向下推时会按预期工作。

CSS:

body {
    background: #bada44
}
.container {
    background: #776;
}
.other {
    background: #ccc;
    /*padding: 1px;*/
}
img {
    width: 33%;
    display: block;
    margin: 0 auto;
    margin-top: 30px;
}

HTML

<div class="container">
    <div class="other">
        <img src="something.jpg" />
    </div>
</div>

jsFiddle:http://jsfiddle.net/mguQY/1/

我正在使用 Chrome

【问题讨论】:

标签: css padding margins


【解决方案1】:

似曾相识:D 将overflow: hidden; 添加到.other

.other {
    background: #ccc;
    /*padding: 1px;*/
    overflow: hidden;
}

http://jsfiddle.net/mguQY/2/

【讨论】:

    【解决方案2】:

    使用 padding-top 代替 margin-top

    【讨论】:

    • 你用 Fiddle 例子检查过吗?
    • 看起来不错;有什么理由添加vertical-align: middle;吗?
    猜你喜欢
    • 2012-03-02
    • 1970-01-01
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 2015-01-26
    • 1970-01-01
    • 2014-11-02
    • 1970-01-01
    相关资源
    最近更新 更多