How to center a DIV with CSS

Centered DIVs

How to center a <div>-Block with CSS? The following code works across all browsers.

  • In examples 01 and 02 we will align a <div> in the middle with and without centering the inside text.
  • Example 03 shows how to center a <div> with floating areas.

Have a look at the examples below and take what suits your needs:

01: Center <div> only

.center-div {
margin-left: auto; margin-right: auto; width: 250px;
}
Demo

This text aligns to the left. However, the surrounding <div> aligns to the center.
Usage:
<div class="center-div"> ... </div>

02: Center <div> with text inside

.center-div-txt {
margin-left: auto; margin-right: auto; width: 250px; text-align: center;
}
Demo

This text and the surrounding <div>
are aligned to the center.
Usage:
<div class="center-div-txt"> ... </div>

03: Center <div> + floating elements

.center-div {
margin-left: auto; margin-right: auto; width: 250px;
} .floatleft-div {
float: left; width: 30%;
} .floatright-div {
float: right; width: 70%;
}
Demo

This is what you see on all examples of this page. The CSS-Codebox floats to the left while the demos are centered around a flexible width.
Usage:
<div class="floatleft-div"> ... </div>
<div class="floatright-div">

<div class="center-div"> ... </div>

</div>

Notes

  • When trying to center a <div>, always specify a width for it. You are free to use any unit (em, px, %, …), but failing to set the width will result in the browser setting it to 100% of the surrounding space. This means the <div> can’t be centered because there is nothing to center.
  • If you only use this element once on a page, you might want to use id instead of class and adjust your CSS from . to #.

That’s it. If you feel like sharing or commenting, you are welcome to do so. Have a nice day.

facebooktwittergoogle_plus

Leave a Reply

Your email address will not be published. Required fields are marked *

2 thoughts on “How to center a DIV with CSS

  1. “When trying to center a , always specify a width for it.”

    Thank you. Just what I needed to know.

    Been a front end developer for over a year and I didn’t know something this basic ๐Ÿ˜€ Used to use jquery to center the div lol :p