2016-10-15 79 views
1

我试着去移动一个div另一个DIV中了一点,但是当我使用CSS移动一个div垂直向下

margin-top: 10px; 

这使得在顶部有一个白色的差距。继承人的HTML:

<div id="topb"> 
    <div id="selection"> 

    </div> 
</div> 

而且继承人的CSS:

#topb { 
    background: url(images/tomato-background.jpg) no-repeat fixed; 
    background-size: cover; 
    height: 100%; 
    width: 101%; 
    margin-left: -10px; 
} 

#selection { 
    background-color: #4d4d4d; 
    width: 60%; 
    height: 500px; 
    margin: auto; 
    margin-top: 40px; 
} 

而且继承人的网站的截图: image

+0

看起来你在#selection中有一个40px的页边距。您的保证金顶部10px在哪里? – Joel

回答

0

也许你可以通过添加padding-top:10px;来修改父元素,而不是修改子元素。

0

在#selection删除边距风格,并应用padding- top to #topb

+0

没有做任何事情。从字面上看。看起来像这样:http://imgur.com/a/eOfPh –

+0

错误的ID,对不起 – Olga

+0

哦,谢天谢地它的作品。谢谢亲爱的 –

0

这是一个“崩溃边缘”问题。 已经回答了这个问题: Why would margin not be contained by parent element?

你将不得不更改父div来:(1)添加边框,(2)位置绝对的,(3)显示为内联块,(4)溢出自动。

请参阅张贴的链接了解更多详情。

0

为此,您可以使用position: absolute。下面是代码:

#topb { 
 
    background: url(images/tomato-background.jpg) no-repeat fixed; 
 
    background-size: cover; 
 
    height: 100%; 
 
    width: 101%; 
 
    margin-left: -10px; 
 
} 
 

 
#selection { 
 
    background-color: #4d4d4d; 
 
    width: 60%; 
 
    height: 500px; 
 
    margin: auto; 
 
    position: absolute; 
 
    top: 40px; /*This is where it is changed as well as the line above*/ 
 
}

希望它能帮助!我认为填充仍然会留下背景,所以这是一个更好的主意。

0

这是工作fiddle希望它可以帮助。

position:absolute; 
position:relative; 
0

这是因为当在另一个块元素中有一个块元素(display:block)时,边距将会折叠。它只会被认为是最大的利润。

因此,在您的示例中,它只会考虑其中一个边距(40px)。 See reference about collapsing margins

有几种解决方法。选择任一:

  1. 使用padding,而不是margin为内部组件。
  2. 更改display类型。例如display: inline-block
  3. 使用absolute定位。