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

时间:2016-09-01 12:29:21

标签: css css3

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

CSS代码:

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

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

1 个答案:

答案 0 :(得分:6)

您可以使用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>

相关问题