Optimus Optimus - 2 months ago 9
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:

parent{
height: 400px;
}
.child{
position:relative;
top:50%;
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?

Answer

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