Optimus Optimus - 24 days ago 5x
CSS Question

Vertically align a child div element with parent div having dynamic height

How do I vertically align a child element with the parent having a dynamic height.

CSS code:

height: 400px;
transform: translateY(-50%;);

This sets the child once, then doesn't change. How do I change it so that it changes with the dynamic height of the parent?


You can use display: flex.

.parent {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 100px;
  width: 100px;
  margin: 1em;
  background-color: tomato;

.child {
  width: 10px;
  height: 10px;
  background-color: yellow;

You can use `displa: flex`.

The following doesn't rely on parent's height.
<div class="parent">
  <div class="child">