saimadan saimadan - 6 months ago 8
CSS Question

Unable to align nested divs properly

I have one main div (page) which has another internal div (central). I applied CSS for both the divs. I gave the margin-top attribute for both the divs separately in CSS, but the margin-top of the internal div is being applied to external div also. How can I fix this problem?

CSS:

#page
{
position: relative;
margin: auto;
margin-top: 40px;
margin-left: auto;
background-color: #b3dced;
height: 900px;
width: 900px;
border-radius: 10px;
}
.central
{
position: relative;
margin: auto;
margin-top: 80px;
background-color: blue;
height: 500px;
width: 500px;
border: 2px solid green;
border-radius: 10px;
}


Align the divs fiddle link

<body>
<div id="page">
<div class="central">
<table>
<tr>
<td>name</td>
<td><input type="text" /></td>
</tr>
<tr>
<td>name</td>
<td><input type="text" /></td>
</tr>
<tr>
<td>name</td>
<td><input type="text" /></td>
</tr>
</table>
</div>
</div>
</body>

Answer

That issue is known as Margin Collapsing.

When the vertical margins of two elements are touching, only the margin of the element with the largest margin value will be honored, while the margin of the element with the smaller margin value will be collapsed to zero.

You could avoid that using padding or top on the child element. Or add a little padding on the parent. Like this:

#page {
  padding-top:1px;
}

Check this http://jsfiddle.net/269Pw/6/.

On this Article you can find more about this issue and many ways to solve it.