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

Mark Caggiano
3 min readApr 30, 2023

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>

--

--