我应该如何垂直对齐具有动态高度的父元素内的子元素。
CSS代码:
parent{
height: 400px;
}
.child{
position:relative;
top:50%;
transform: translateY(-50%;);
}
这将子元素设置一次,然后不再更改。如何更改它以使其随父元素的动态高度而更改?
我应该如何垂直对齐具有动态高度的父元素内的子元素。
CSS代码:
parent{
height: 400px;
}
.child{
position:relative;
top:50%;
transform: translateY(-50%;);
}
这将子元素设置一次,然后不再更改。如何更改它以使其随父元素的动态高度而更改?
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>
100%
,因为100%
表示其父级的100%
,而.parent
的父级没有指定的大小。您可以调整宽度和高度,并查看无论您将其更改为什么,它都将保持在完美的中心位置。该代码不依赖于parent
的width
和height
属性。 - Lazar Ljubenović