为什么要设置这个子元素的顶部边距以及它的父容器? [英] Why is setting the top-margin of this child element pushing its parent container down with it?

查看:194
本文介绍了为什么要设置这个子元素的顶部边距以及它的父容器?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个div:

<div id="headercontainer" data-type="background" data-speed="5"> 
    <div id="headersubcontainer">
        <h1>Simple and Cost Effective Web Solutions</h1>  
    </div> 
</div>

<div id="teamcontainer" data-type="background" data-speed="5"> 
    <div id="teamsubcontainer"> 
        <h1>Developed by a dedicated team</h1> 
    </div> 
</div> 

都有100%的宽度和高度为800像素。第一个标题我设置了一个160像素的顶部边距。

both have 100% widths and heights of 800px. The first heading I have set a top-margin: of 160px. Instead of moving the header lower into its parent div, it moves the parent div down with it as you can see in this picture:

这是我的相关CSS:

h1{
    font-size: 48px;
    font-family: $header-font-stack; 
    font-weight: 100;
    width: 400px;
}

#headercontainer{
    width: 100%; 
    height: 800px;
    background-image: image-url("background.jpg");
    background-position: center top;
    background-repeat: no-repeat;
}

#headercontainer h1{
    text-align: center;
    margin: 0px auto;
    margin-top: 160px;
    color: #610B21;
}

使用填充显然,但我想更适当,保证金。如何设置顶边距并将标题向下移动到容器中,而不移动容器?

Using a padding works obviously, but I would like to be more proper and use a margin. How can set a top margin and move the heading lower into the container without moving the container with it?

推荐答案

这是由于 保证金收入


有时将
合并(折叠)到单个边距中,该边距的大小是将
组合到其中的最大边距,即被称为边距折叠的行为。

Top and bottom margins of blocks are sometimes combined (collapsed) into a single margin whose size is the largest of the margins combined into it, a behavior known as margin collapsing.

这导致父元素反向继承子元素顶部边距。

This is resulting in the parent element reverse-inheriting the child element top margin.

您可以通过添加& nbsp;

....或将以下任何内容应用于父级:

....or applying any of the below to the parent:


  1. float:left / right

  2. position:absolute

  3. display:inline-block

向父项添加 display:inline-block; 可能是偏好设置, width to 100%

Adding display:inline-block; to the parent likely being the preference if it is set to have a width to 100%

这篇关于为什么要设置这个子元素的顶部边距以及它的父容器?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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