Margin-top affects inner and outer elements, but margin-left is not anchorage.

If I add margin-top: 50px;

to #box

, then #container

also gets margin-top

, but if I add #margin-left: 50px

to #box

, then why not #container

get 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;
}

      

+3


source to share


5 answers


You can do what you want by adding possition:fixed

to the container like here .



+1


source


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

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

}

      



hope this helps

0


source


Welcome to the crazy world of crumbling fields.

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

In CSS, adjacent margins of two or more boxes (which may or may not be siblings) can be combined to form a single stock. It is believed that the fields that are combined in this way collapse, and the resulting combined stock is called the compensated stock.

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

0


source


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

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

Quoting from W3C article: "Horizontal margins never collapse."

Also from the W3C there are several vertical field methods that deal with collapse, including:

  • If "there are no lines, no gaps, no indents and no borders"
  • both items belong to the adjacent edges of the box, "the top of the box and the top of its first flow child"

A good way to prevent this is to assign a 30px top margin to the parent, and also assign a 10px top margin to the parent. This moves the parent down 30 pixels and also moves it down 10 pixels.

See this similar question for more information: Margin on child moves parent

#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;
    }

      

0


source


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

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

      

fiddle

0


source







All Articles