3

If I add margin-top: 50px; to #box then #container is also getting margin-top, but If I add #margin-left: 50px to #box then why isn't #container getting margin-left?

Fiddle

HTML:

<body>
  <div id="container">
    <div id="box">box</div>
  </div>
</body>

CSS:

#container {
    width: 500px;
    height: 500px;
    background-color: gray;
    margin-top: 30px;
    margin-left: 30px;
}
#box {
    width: 100px;
    height: 100px;
    background-color: orange;
    margin-top: 10px;
}
Weafs.py
  • 22,731
  • 9
  • 56
  • 78

5 Answers5

1

You can do what you want by adding possition:fixed to the container like here.

Florin Pop
  • 5,105
  • 3
  • 25
  • 58
0

Please add for #box float:left. Update your css with

#box {
    width: 100px;
    height: 100px;
    background-color: orange;
    margin-top: 20px;
    margin-left:25px;
    float : left;

}

hope this will help

Azeez Kallayi
  • 2,567
  • 1
  • 15
  • 19
0

Welcome to the crazy world of collapsing margins.

http://www.w3.org/TR/CSS2/box.html#collapsing-margins

In CSS, the adjoining margins of two or more boxes (which might or might not be siblings) can combine to form a single margin. Margins that combine this way are said to collapse, and the resulting combined margin is called a collapsed margin.

You could add a transparent border on the outer div, use padding, or float the inner div with a clearfix on the outer div.

LUKE
  • 1,375
  • 11
  • 9
0

This is how the Margin Collapse works. Here are the details from W3C:

http://www.w3.org/TR/CSS2/box.html#collapsing-margins

Quoted from the W3C article, "Horizontal margins never collapse."

Also from W3C, there are several ways vertical margins that touch collapse including:

  1. If "no line boxes, no clearance, no padding and no border separate them"
  2. both elements belong to adjacent box edges, "top margin of a box and top margin of its first in-flow child"

A good way to prevent this is to assign the 30px top margin to the parent, and also assign 10px top padding to the parent. This moves the parent down by 30px and also moves the child down by 10px.

Please see this similar question for more info: Margin on child element moves parent element

#container {
        width: 500px;
        height: 500px;
        background-color: gray;
        margin-top: 30px;
        margin-left: 30px;
        padding-top:10px;
    }
    #box {
        width: 100px;
        height: 100px;
        background-color: orange;
        margin-top: 0px;
    }
Talkingrock
  • 789
  • 6
  • 7
0

try using padding in #container instead of margin in #box or use them both like this:

#container
{
   padding-top: 1px;
   padding-left: 1px;
}
#box
{
  margin-top: 100px;
  margin-left: 100px;
}

fiddle

user3926604
  • 179
  • 2
  • 12