DEV Community

Cover image for CSS Interview Question: Center HTML Element (3 Approaches💥)
Let's Code
Let's Code

Posted on

CSS Interview Question: Center HTML Element (3 Approaches💥)

You get asked a question ❓ or is challenged to write code to

Center a div vertically and horizontally OR How to perfectly center an element in a browser?

How would you answer? 🤔 Below are three possible ways to do it. My recommendation all the way below. Given HTML markup that looks like below:

<div class="parent">
  <div class="child"></div>
</div>
Enter fullscreen mode Exit fullscreen mode

Approach #1: CSS Translate/Transform
This is an approach that have a better browser 🌏 support than both CSS Flexbox and Grid. Code may look like below.

.parent {
  position: relative;
}

.child {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}
Enter fullscreen mode Exit fullscreen mode

CSS Translate/Transform Browser Support Image

Codepen: https://codepen.io/angelo_jin/pen/popONyX

Note: All implementation will look like below

Vertically and Horizontally Centered HTML Element

Approach #2: CSS Flexbox
This solution have a better browser support than css grid and ideal for those browsers can support the feature. It is great for creating 1 dimension layout which aims at providing a more efficient way to align and distribute space among items in a container. Can even center when their size is unknown and/or dynamic. 😲

.parent {
  display: flex;
  align-items: center;
  justify-content: center;
}
Enter fullscreen mode Exit fullscreen mode

Codepen: https://codepen.io/angelo_jin/pen/QWaVGGP

CSS Flexbox Browser Support Image

Approach #3: CSS Grid
This ruleset is ideal because we are not on the 90's anymore, few lines of style we have to add that completely changes the way we design user interface.😊 CSS Grid Layout excels at dividing a page into major regions or defining the relationship in terms of size, position, and layer, between parts of a control built from HTML primitives.

If you are going to use this on your interview, mention that you would use this solution if browser can support it. This would show that you are paying attention with the latest and greatest css specs and is not tied up with the old way of doing things.

// CSS Grid
.parent {
  display: grid;
  place-items: center;
}
Enter fullscreen mode Exit fullscreen mode

Codepen: https://codepen.io/angelo_jin/pen/qBpMqRr

CSS Grid Browser Support Image

Below is for medium for those who like video format:

Codepen Center Element Collection: https://codepen.io/collection/MgJxRk
(Great idea to bookmark for future use)

A great front-end engineer focus his attention equally on CSS and JS, be well-rounded, and doesn't concentrate on one technology. For my recommendation on this question, I would use CSS Grid if browser is capable of supporting. If not, resort to CSS Flexbox then, CSS Translate would be the last choice.

Top comments (0)