CSS – align div in center horizontally

Div (when a block level element) or any other block level element can be aligned in center of its container using property margin-left:auto and margin-right:auto. Note that When div is inline-block this approach won’t work. Here are some examples.

Align div in middle horizontally

Here inner div is aligned in center using margin:auto. Not that text within center div is not aligned in center.

<style type="text/css">
.container {
  width: 300px;
  height:150px;
  background-color:lightgreen;
}
.inner {
  margin:auto;
  background-color:lightgray;
  width: 200px; height: 100px;
}
</style>

<div class="container">
  <div class="inner">Hello world</div>
</div>
refresh

Align h1 in middle horizontally

Here inner h1 is aligned in center using margin:10px auto. Not that text within h1 is not aligned in center.

<style type="text/css">
.container {
  width: 300px;
  height:150px;
  background-color:lightgreen;
}
.inner {
  margin:10px auto;
  background-color:lightgray;
  width: 200px;
}
</style>

<div class="container">
  <h1 class="inner">Hello world</h1>
</div>
refresh

Share this article: share on Google+ share on facebook share on linkedin tweet this submit to reddit

Comments

Click here to write/view comments