Optimus Optimus - 3 months ago 11
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:

parent{
height: 400px;
}
.child{
position:relative;
top:50%;
transform: translateY(-50%;);
}


But what if the height of parent is dynamic??

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>