DevDose: Three Ways to Centre a div with CSS

Day Seven of Dailydose

This came up while mentoring a junior developer who was puzzled by layout inconsistencies. We explored different centring techniques and why they behave the way they do.

One real-world case was a login box that wouldn’t stay centred in all screen sizes. We tested a few methods to find the one that best respected responsiveness and minimal CSS.

Here are three standard techniques for centring a div both vertically and horizontally:

/* Flexbox */
.parent {
  display: flex;
  justify-content: center;
  align-items: center;
}

/* Grid */
.parent {
  display: grid;
  place-items: center;
}

/* Margin Auto (horizontal only, needs fixed width) */
.child {
  margin: 0 auto;
  width: 200px;
}

Each method solves a slightly different problem. margin: auto works well for horizontal centring of fixed-width elements. display: flex is more flexible and widely used, especially when vertical alignment is also needed. grid with place-items: center is concise and powerful, but less commonly used outside of fully grid-based layouts.

In mentoring or code review, I prefer starting with flexbox for its balance of clarity and control, then switching based on project constraints.

Choose the method that matches the layout’s intent and scale.

Comments

Leave a Reply

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