Optimus Optimus - 1 year ago 64
CSS Question

Vertically align a child element with parent having dynamic height

How to vertically align a child element with parent having a dynamic height. What I use is:

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

But what if the height of parent is dynamic??

Answer Source

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">