I have a div
(parent) that contains another div
(child). Parent is the first element in body
with no particular CSS style. When I set
.child
{
margin-top: 10px;
}
The end result is that top of my child is still aligned with parent. Instead of child being shifted for 10px downwards, my parent moves 10px down.
My DOCTYPE
is set to XHTML Transitional
.
What am I missing here?
edit 1
My parent needs to have strictly defined dimensions because it has a background that has to be displayed under it from top to bottom (pixel perfect). So setting vertical margins on it is a no go.
edit 2
This behaviour is the same on FF, IE as well as CR.
I had this problem too but preferred to prevent negative margins hacks, so I put a
<div class="supercontainer"></div>
around it all which has paddings instead of margins. Of course this means more divitis but it's probably the cleanest way to do get this done properly.
add style
display:inline-block
to child elementinterestingly my favorite solution to this problem isn't yet mentioned here: using floats.
html:
css:
see it here: http://codepen.io/anon/pen/Iphol
note that in case you need dynamic height on the parent, it also has to float, so simply replace
height:100px;
byfloat:left;
The
margin
of the elements contained within.child
are collapsing.In this example,
p
is receiving amargin
from the browser default styles. Browser defaultfont-size
is typically 16px. By having amargin-top
of more than 16px on#child
you start to notice it's position move.An alternative solution I found before I knew the correct answer was to add a transparent border to the parent element.
Your box will use extra pixels though...
Using
top
instead ofmargin-top
is another possible solution, if appropriate.