Step-by-step tutorial on how to center a div using CSS, with examples of different methods

Mark Caggiano
3 min readApr 30

Here’s a step-by-step tutorial on how to center divs using CSS, with examples of different methods.

Method 1: Using position

This method uses the position property to center the div horizontally and vertically.

  • Create a div element in your HTML code:
<div class=”centered”>
<p>Centered content goes here</p>
</div>
  • Apply the following CSS rules to the div element:
.centered {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}

The position property is set to absolute so that the div can be positioned relative to its containing element. The top and left properties are set to 50% to move the div halfway down and halfway across the containing element. The transform property is used to shift the div up and to the left by 50% of its own width and height.

Method 2: Using Flexbox

This method uses the Flexbox layout model to center the div horizontally and vertically.

  • Create a div element in your HTML code:
<div class="flex-centered">
<p>Centered content goes here</p>
</div>
  • Apply the following CSS rules to the containing element:
.container {
display: flex;
justify-content: center;
align-items: center;
}

The display property is set to flex to enable the use of the Flexbox layout model. The justify-content property is set to center to center the div horizontally, and the align-items property is set to center to center the div vertically.

Method 3: Using Grid

This method uses the CSS Grid layout model to center the div horizontally and vertically.

  • Create a div element in your HTML code:
<div class="grid-centered">
<p>Centered content goes here</p>
</div>
  • Apply the following CSS rules to the containing element:
.container {
display: grid;
place-items: center;
}
Mark Caggiano

Internet Marketer, Web Developer, Traveler