Back to all posts

CSS: How to center a div


To center a `<div>` using CSS, there are several methods you can use depending on your layout and design requirements.

Here some most common ways:

Method 1: Using margin

Method 2: Using Flexbox

Methos 3: Using Grid


Method 1: Using margin property with auto value

Set the left and right margin of the ‘<div>‘ to ‘auto‘ and give it a fixed width. This will center the <div> horizontally within its parent container.

Example

<!-- HTML -->
<div class="container">
  <div class="centered">
    <!-- Your content goes here -->
  </div>
</div>
/*CSS*/

.container {
  width: 150px;
  margin: 0 auto;
  padding:50px;
  background:darkblue;
}

.centered {
  width: 100px;
  height:100px;
  background:skyblue;
  margin: 0 auto;
}

See the Pen Center A Div Using Margin by Chethan S Poojary (@chethanspoojary) on CodePen.


Method 2: Using Flexbox

Set the left and right margin of the ‘<div>‘ to ‘auto‘ and give it a fixed width. This will center the <div> horizontally within its parent container.

Example

<!-- HTML -->
<div class="container">
  <div class="centered">
    <!-- Your content goes here -->
  </div>
</div>
/*CSS*/


.container {
  background:darkblue;
  display: flex;
  justify-content: center;
  align-items: center;

  height: 300px;
}

.centered {

  width: 100px;
  height:100px;
  background:skyblue;
}

See the Pen Center A Div Using Flexbox by Chethan S Poojary (@chethanspoojary) on CodePen.


Method 3: Using CSS Grid

CSS Grid can be used to center a ‘<div>’ both horizontally and vertically. to do this, set the parent container’s display property to ‘grid’ and use the ‘place-items’ property to center the child element.

Example

<!-- HTML -->
<div class="container">
  <div class="centered">
    <!-- Your content goes here -->
  </div>
</div>
/*CSS*/
.container {
  background:darkblue;
  display: grid;
  place-items: center;
  height: 300px;
}

.centered {
  width: 100px;
  height:100px;
  background:skyblue;
}

See the Pen Untitled by Chethan S Poojary (@chethanspoojary) on CodePen.