简体   繁体   中英

CSS moving a div vertically down

Im trying to move a div inside another div down a bit, but when I use

margin-top: 10px;

It makes a white gap at the top. Heres the html:

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

    </div>
</div>

And heres the 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;
}

And heres a screenshot of the website: 图片

删除#selection中的margin-top样式,并将padding-top应用于#topb

This is a "collapsed margin" problem. It has been answered in this question : Why would margin not be contained by parent element?

You would have to change the parent div to either (1) add a border, (2) position absolute, (3) display as inline-block, (4) overflow auto.

Refer to the posted link for more detail.

maybe you can modify the parent element by adding padding-top:10px; instead of modifying the child.

For this, you can use position: absolute . Here is the code:

 #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*/ } 

Hope it helps! I think padding would still leave a background, so this is a better idea.

Here is the working fiddle Hope it may help.

position:absolute;
position:relative;

This is because when you have a block element (display: block) inside another block element, the margins will collapse. It will only be considered the largest margin.

So, in your example it will only consider one of the margins (40px). See reference about collapsing margins .

There are a few workarounds. Choose any:

  1. using padding instead of margin for the component inside.
  2. Change display type. eg display: inline-block .
  3. Use absolute positioning.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM