Centering divs
Centering divs
Jun 13I often get asked how to properly align divs and containers on website pages.
The most common bugbear is centering divs either vertically and horizontally, which can be a pain unless you know how.
This post has three examples of how to position the divs and should help clear up any confusion you may have.
Text is simple to align with css using the “text-align” property, as below:
// CSS
.positionme { text-align:center }
// HTML
<div class="positionme">
Position Me!
</div>
</pre>
.positionme { text-align:center }
// HTML
<div class="positionme">
Position Me!
</div>
</pre>
Positioning a div to center vertically and horizontally is a little trickier, but easy when you know how!
Let’s start with centering the div horizontally:
// CSS
.positionme { text-align:center; width:250px; margin:auto auto }
// HTML
<div class="positionme">
Position Me!
</div>
</pre>
.positionme { text-align:center; width:250px; margin:auto auto }
// HTML
<div class="positionme">
Position Me!
</div>
</pre>
We can use a similar trick to get the div positioned centered vertically too:
// CSS
.positionme { text-align:center; width:250px;height:250px;
left:50%; top:50%;
margin:-125px 0 0 -125px;
}
// HTML
<div class="positionme">
Position Me!
</div>
</pre>
.positionme { text-align:center; width:250px;height:250px;
left:50%; top:50%;
margin:-125px 0 0 -125px;
}
// HTML
<div class="positionme">
Position Me!
</div>
</pre>