2

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: image

Lachlan Mather
  • 135
  • 2
  • 5
  • 14
  • It looks like you have a margin top of 40px in the #selection. Where is your margin top of 10px? – Joel Oct 15 '16 at 22:11

6 Answers6

2

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.

Umair Khan
  • 307
  • 1
  • 5
1

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

n1kkou
  • 3,096
  • 2
  • 21
  • 32
0

Remove margin-top style in #selection, and apply padding-top to #topb

Olha Vadiasova
  • 418
  • 6
  • 16
0

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.

Community
  • 1
  • 1
Simon
  • 2,353
  • 1
  • 13
  • 28
0

Here is the working fiddle Hope it may help.

position:absolute;
position:relative;
Pritish Vaidya
  • 21,561
  • 3
  • 58
  • 76
0

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 marginfor the component inside.
  2. Change display type. e.g. display: inline-block.
  3. Use absolute positioning.
Edmar Miyake
  • 12,047
  • 3
  • 37
  • 38