Search code examples
csspositioning

How to position absolute inside a div?


I'm having a strange problem positioning a set of divs inside another div. I think it will be best to describe it with an image:

image

Inside the black (#box) div there are two divs (.a, .b) that have to positioned in the same place. What I'm trying to achieve is pictured in the first image, second one is the effect I get. It looks like if the divs were floated without clearing or something, which is obviously not the case. Any ideas would be welcome!

Here's the code for this sample:

CSS:

#box {
    background-color: #000;
    position: relative;
    padding: 10px;
    width: 220px;
}

.a {
    width: 210px;
    position: absolute;
    top: 10px;
    left: 10px;
    background-color: #fff;
    padding: 5px;
}

.b {
    width: 210px;
    position: absolute;
    top: 10px;
    left: 10px;
    background-color: red;
    padding: 5px;
}

#after {
    background-color: yellow;
    padding: 10px;
    width: 220px;
}

HTML:

    <div id="box">
        <div class="a">Lorem</div>
        <div class="b">Lorem</div>
    </div>

    <div id="after">Hello world</div>

Solution

  • The absolute divs are taken out of the flow of the document so the containing div does not have any content except for the padding. Give #box a height to fill it out.

    #box {
        background-color: #000;
        position: relative;
        padding: 10px;
        width: 220px;
        height:30px;
    }