子元素上的边距移动父元素 [英] Margin on child element moves parent element

查看:182
本文介绍了子元素上的边距移动父元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 div )包含另一个 div >子)。 Parent是 body 中没有特定CSS样式的第一个元素。当我设置

  .child 
{
margin-top:10px;
}

最后的结果是我的孩子的顶部仍然与父对齐。



我的 DOCTYPE 设置为 XHTML Transitional



我在这里缺少什么?

编辑1

我的父级需要严格定义维度,因为它的背景必须从下到上显示在下面)。因此,在其上设置垂直边距是无效



编辑2

解决方案

在DIV中使用边距的元素您还可以添加:

  .parent {overflow:auto; } 

或:

  .parent {overflow:hidden; } 

这可防止边距 collapse 。边框和填充也是一样。
因此,您还可以使用以下方法防止顶部合约崩溃:

  .parent {
padding-top:1px;
margin-top:-1px;
}






热门请求:
折叠边距的整点是处理文本内容。例如:

 < style type =text / css> 
h1,p,ul {
margin-top:1em;
margin-bottom:1em;
}
< / style>

< h1>标题!< / h1>
< div>
< p>段落< / p>
< ul>
< li>列表项< / li>
< / ul>
< / div>

因为浏览器折叠边距,所以文本会按预期显示。
每个元素确保它周围有间距,但是间距不会加倍。
< h1> < p> 的边距不会相加,坍方。
对于< p> < ul> 元素也是如此。

很遗憾,在现代设计中,这个想法可能会在你明确想要一个容器时咬你。这称为CSS中的新阻止格式设置上下文溢出或利润技巧会给你。


I have a div (parent) that contains another div (child). Parent is the first element in body with no particular CSS style. When I set

.child
{
    margin-top: 10px;
}

The end result is that top of my child is still aligned with parent. Instead of child being shifted for 10px downwards, my parent moves 10px down.

My DOCTYPE is set to XHTML Transitional.

What am I missing here?

edit 1
My parent needs to have strictly defined dimensions because it has a background that has to be displayed under it from top to bottom (pixel perfect). So setting vertical margins on it is a no go.

edit 2
This behaviour is the same on FF, IE as well as CR.

解决方案

Found an alternative at Child elements with margins within DIVs You can also add:

.parent { overflow: auto; }

or:

.parent { overflow: hidden; }

This prevents the margins to collapse. Border and padding do the same. Hence, you can also use the following to prevent a top-margin collapse:

.parent {
    padding-top: 1px;
    margin-top: -1px;
}


Update by popular request: The whole point of collapsing margins is handling textual content. For example:

<style type="text/css">
    h1, p, ul {
        margin-top: 1em;
        margin-bottom: 1em;
    }
</style>

<h1>Title!</h1>
<div>
    <p>Paragraph</p>
    <ul>
        <li>list item</li>
    </ul>
</div>

Because the browser collapses margins, the text would appear as you'd expect. Each element ensures it has spacing around it, but spacing won't be doubled. The margins of the <h1> and <p> won't add up, but collapse. The same happens for the <p> and <ul> element.

Sadly, with modern designs this idea can bite you when you explicitly want a container. This is called a new block formatting context in CSS speak. The overflow or margin trick will give you that.

这篇关于子元素上的边距移动父元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆