Absolutely position an element within another element with CSS

Posted in HTML and CSS -

When an element is positioned absolutely with CSS it is by default relative to the window as a whole and not to the parent element. This post shows how to absolutely position an element within another element with CSS.

The following screenshot shows what we are trying to achieve. The black boxes labelled "right div" in the screenshot below have the following CSS:

.right {
    position: absolute;
    right: 10px;
    top: 10px;
    height: 50px;
    width: 50px;
    background-color: black;
    color: white;
}

As you can see the top right div is positioned 10px off the right side of the browser viewport and 10px below the top of the viewport. The second right div is absolutely positioned within the containing div.

absolute position example

If the window is resized the top right div remains at right:10px and top:10px relative to the viewport but the bottom right div remains in exactly the same place, relative to the containing div.

example of absolute vs absolute-relative positioning

So how is this done? It's very easy, simple set the following for the containing div:

position: relative;

The full CSS for the above example is below:

.main {
    width: 300px;
    height: 70px;
    background-color: #ccc;
    margin-bottom: 10px;
}
.right {
    position: absolute;
    right: 10px;
    top: 10px;
    height: 50px;
    width: 50px;
    background-color: black;
    color: white;
}
.relative {
    position: relative;
}

And the HTML:

<div class="main">
    300px div
    <div class="right">
        right div
    </div>
</div>

<div class="main relative">
    300px div - relative
    <div class="right">
        right div
    </div>
</div>


Related posts:


Comments