CSS position: absolute

 

ATTENTION: THIS PAGE IS Valid HTML 5 AND IS BEST VIEWED WITH HTML 5 - Please upgrade your browser or download one of the HTML 5 compatible browsers such as Mozilla Firefox, Chrome, Opera or IE 9 (March 14, 2011 or later). For more information see HTML 5 browsers.


If you find this helpful, please click the Google +1 Button to the left, if it is white, to make it turn blue or red. Thank you! (It also helps find this page again more easily.)


PDF mobile

CSS position: absolute

In the following example the <div> with the blue border is positioned in the center of the page and its contents are also centered.

This paragraph is positioned at the top of the <div> and its contents are left justified.

This paragraph is centered at the bottom of the <div> and its contents are left justified.


<div> with paragraph centered at bottom

<style type="text/css">
p {
   margin-top: 8px;
   margin-bottom: 8px;
   padding: 0 0.3em;
}
.blue-border {
   border: 2px solid #0000cc;
}
.green-border {
   border: 2px solid #009900;
}
.relative {
   width: 70%;
   height: 250px;
   position: relative;
}
.bottom {
   position: absolute;
   bottom: 0;
   left: 20%;
   width: 60%;
}
.center {
   margin-left: auto;
   margin-right: auto;
}
.left-justified {
   text-align: left;
}
.centered {
   text-align: center;
}
</style>
<div class="relative center blue-border centered">
   <p class="left green-border left-justified">This paragraph is positioned at the top of the <div> and its contents are left justified.</p>
   <p class="bottom-60pct green-border left-justified">This paragraph is centered at the bottom of the <div> and its contents are left justified.</p>
</div>

The contents of the <div> are positioned relative to the <div> itself using position: relative. It is centered with margin-left: auto and margin-right: auto and its contents are centered with text-align: center.

To position the paragraph at the bottom of the div, the bottom-60% style includes position: absolute and bottom: 0. Since margin: auto does not work for centering a paragraph when using absolute positioning, left: 20% sets the absolute left position to half the space not used by the paragraph element (20% = one half of 100% minus 60%).


Valid HTML 5