HTML/CSS - 2 column layout, right side top-margin affects left side too
Here's my simple mark-up:
<div style="width:200px">
<div style="width:50%;floa开发者_运维技巧t:left;">
left side
</div>
<div style="margin-left:50%;width:50%;margin-top:10px;">
right side
</div>
</div>
The problem is that the margin-top:10px; on the right side also pushes down the left side. What am I missing here? is this expected? I would like to adjust the left and right sides top-margin properties independently
There are a few things you can do. What is happening is the right div's margin is affecting the position of the containing div for both, which is what pushes the left one down. I believe this is expected behavior. Any of these can work:
- Set the containing div to
float: left
- Counter act the right div by either setting a -10px margin on the containing div or on the left div.
This is called margin collapsing and what actually happens is that because the outer div (the width:200px
) is empty, it takes its children margin and uses it instead of the children.. so the container gets pushed down 10px and since the left/right divs are inside it they move as well..
"the expression collapsing margins means that adjoining margins (no non-empty content, padding or border areas or clearance separate them) of two or more boxes (which may be next to one another or nested) combine to form a single margin."
if you give it a border you will see it work as expected.. demo
Try floating the div wrapping the two columns, and also the right side div
精彩评论