Easy change margin / marginal left

Enlighten me with the question:

If I put a div inside another, in this second div I cannot use the margin-left and margin-top properties without changing the position of the parent div?

Do I need to use padding instead?

Exemple:

FIDDLE WITH MARGINS: http://jsfiddle.net/zyEYj/1/

FIDDLE WITHOUT MARGINS: http://jsfiddle.net/zyEYj/2/

FIDDLE WITH PADDING INSIDE MOTHER DIV: http://jsfiddle.net/zyEYj/3/ (this is the last effect I want, but I need to #header and change the height of #header )

codes:

 <div id="header" class="container"> <div class="logo"> <a href="index.asp"><img src="imagens/logo.png" /></a> </div> </div> 

CSS

 body{ background:#d3f1fc; } #header{ height:135px; background:#ee4b14; padding-top:35px; padding-left:21px; } .container { margin:0 auto; width:960px; } .logo{ width:382px; height:114px; background:#FFCC00; }​ 
+4
source share
3 answers

This behavior is called margin collapse . Two adjacent fields will fall apart, with a higher absolute value taking precedence.

This can be defeated by dividing the fields (via padding or border by the parent) or by using position: relative in the child and adjusting it this way.

HTML:

 <div class="parent"> <div class="child"></div> </div> 

CSS

Normal

 /* these margins will collapse, and result in a total margin of 15px */ .parent { margin: 5px; } .child { margin: 15px; } 

Filling / Boundary Solution

 /* these margins will be separate, resulting in a total margin of 20px plus the border or padding of 1px */ .parent { margin: 5px; padding: 1px; /* or border: 1px; */ } .child { margin: 15px; } 

Position: relative decision

 /* there is only one margin here, and the child is positioned relative to where it would usually be rendered */ .parent { margin: 5px; } .child { position: relative; top: 15px; } 
+3
source

This is normal behavior. http://www.w3.org/TR/CSS2/box.html - good reading to better understand.

You will need to use padding for the parent to move the child top.

Like this: http://jsfiddle.net/88ATa/

Sincerely. Jonas

+1
source

One way to solve this problem would be to place the div container in its absolute position, so that the inner div has its limits limited by the border of the container. So juste adds

 .container { position:absolute; } 

will work. But for some reason, absolute positioning may not be what you are looking for. This may change your page layout, for example.

See: http://jsfiddle.net/zyEYj/13/

0
source

All Articles