将子div元素与具有动态高度的父div垂直对齐

Opt*_*mus 5 css css3

如何将子元素与具有动态高度的父元素垂直对齐.

CSS代码:

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

这会将孩子设定一次,然后不会改变.如何更改它以使其随父项的动态高度而变化?

Laz*_*vić 7

你可以用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.
Run Code Online (Sandbox Code Playgroud)
<div class="parent">
  <div class="child">
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)