css实现水平垂直居中的4种方法
html结构:
<div class="parent">
<div class="item"></div>
</div>1. 已知元素的宽度和高度:
.item {
position: absolute;
top: 50%;
left: 50%;
margin-top: -75px; /* 设置margin-left / margin-top 为自身高度的一半 */
margin-left: -75px;
}.item {
position: absolute;
margin:auto;
left:0;
top:0;
right:0;
bottom:0;
}
/* 这个方法可以实现自适应 */2. 未知元素的高度和宽度:
.item {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%); /* 使用css3的transform来实现 */
}.parent {
display: flex;
justify-content:center;
align-items: center;
background: #AAA;
height: 300px; /* 注意这里需要设置高度来查看垂直居中效果 */
} 相关推荐
drdrsky 2020-06-16
PioneerFan 2020-06-10
HSdiana 2020-03-28
葉無聞 2020-03-23
lyg0 2020-03-07
冰蝶 2020-01-10
玫瑰小妖 2019-12-31
行吟阁 2019-12-08
aiolos 2016-04-15
loverlucky 2016-03-15
云端漂移 2019-07-01
renpinghao 2019-06-30
kbkiss 2019-06-29