2

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>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
saimadan
  • 173
  • 2
  • 12

2 Answers2

3

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.

DaniP
  • 37,813
  • 8
  • 65
  • 74
1

There are different ways to do this. Details are in Stack Overflow post Position an HTML element relative to its container using CSS about using position: relative.

But sometimes it is easier to learn based on your own code:

#page
{
    position: relative;
    margin-top: 40px;
    margin-left: auto;
    margin-right: auto;
    background-color: #B3DCED;
    height: 900px;
    width: 900px;
    border-radius: 10px;
}
.central
{
    position: absolute;
    margin-top: 80px;
    margin-left: 200px;
    margin-right: 200px;
    background-color: blue;
    height: 500px;
    width: 500px;
    border: 2px solid green;
    border-radius: 10px;
}
Community
  • 1
  • 1