iitum studant
iitum studant

Reputation: 866

Divs with children not stacking properly

Please take a look at this fiddle https://jsfiddle.net/t2w4yd8j/1/

I have a couple of questions about this:

1) There seems to be a padding between the .top div(red) and the browser if I use the relative position. However if I change the position of .top div(red) to absolute the padding goes off. Why is that?

2) The .next div(pink) should stack after the .main div(grey). But the main div seems to be taking a bit more extra space even though the height is set to auto and there is no children in the extra space. Why is that?

Thanks

CSS

.main{
    height:auto;
    width:100%;
    text-align:center;
    background-color:#CCC;
}
.top{
    position:relative;
    top:0px;
    left:0px;
    width:100%;
    height:50px;
    background-color:#F00;
}
.middle{
    position:relative;
    top:-25px;
    width:100%;
    height:auto;
    text-align:center;
    z-index:3;
}
.midfill{
    width:200px;
    height:50px;
    display: inline-block;
    background-color:#0F0;
}
.bottom{
    position:relative;
    top:-50px;
    left:0px;
    width:100%;
    height:50px;
    background-color:#00F;
}

.next{
    width:100%;
    height:100px;
    background-color:#F0F;
}

HTML

 <div class="main">
        <div class="top"></div>
        <div class="middle">
            <div class="midfill"></div>
        </div>
        <div class="bottom"></div>
    </div>
    <div class="next"></div>

Upvotes: 2

Views: 682

Answers (2)

GreyRoofPigeon
GreyRoofPigeon

Reputation: 18133

1) By placing it relative, it relates to it's parent, the body tag. Remove the padding and margin from the body and HTML tag, and it fits. When you place the div absolute, it's taking out of the document flow, making it relate to the viewport. That explains the difference.

html, body { margin: 0; padding: 0; }

2) you position the div's relative, and then move them around. But the place stays reserved in the parent div. I moved the divs a bit around.

html, body { 
    margin: 0; 
    padding: 0; 
}
.main{
    height:auto;
    width:100%;
    text-align:center;
    background-color:#CCC;
}
.top{
    width:100%;
    height:50px;
    background-color:#F00;
}
.middle{
    position: absolute;
    margin-top: -25px;
    width:100%;
    height:auto;
    text-align:center;
    z-index:3;
}
.midfill{
    display: inline-block;
    width:200px;
    height:50px;
    background-color:#0F0;
}
.bottom{
    width:100%;
    height:50px;
    background-color:#00F;
}

.next{
    width:100%;
    height:100px;
    background-color:#F0F;
}

Updated Fiddle

Upvotes: 2

ketan
ketan

Reputation: 19341

Solution for your both problem is following. By Default it takes extra margin by removing it from body solved your issue:

body{
    padding:0;
    margin:0;
}

Check Fiddle Here.

Upvotes: 1

Related Questions