Absolutely position an element within another element with CSS
Posted May 30th, 2009 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.

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.

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:
- Using CSS letter-spacing to space out titles (Saturday, April 18th 2009)
- Blockquotes and XHTML Strict (Saturday, April 11th 2009)
- Valid characters for the HTML ID attribute (Saturday, April 4th 2009)
- Add an offsite link icon after external links with CSS (Friday, March 27th 2009)
- Force reload of updated CSS and Javascript files with unique filenames (Friday, March 20th 2009)
- Wide background image header with CSS (Saturday, March 14th 2009)

Comments
blog comments powered by Disqus