考题:一个300*300的div在不同分辨率屏幕中上下左右居中,如何用css
实现?
一、绝对定位方法:设置margin-left,margin-top值为当前div宽高一半的负值
.Center {
width: 300px;
height: 300px;
background: wheat;
position: absolute;
left: 50%;
top: 50%;
margin-left: -150px;
margin-top: -150px;
}
二、绝对定位方法:上下左右值都设置为0 (margin:auto居中)
.Center {
width: 300px;
height: 300px;
background-color: yellowgreen;
position: absolute;
margin: auto;
left: 0;
right: 0;
bottom: 0;
top: 0;
}
三、translate()方法,根据左(X轴)和顶部(Y轴)位置给定的参数,从当前元素位置移动。
.
Center {
width: 300px;
height: 300px;
background:gold;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
四、相对定位方法(position: relative;):设置margin-left值为当前高的一半
.Center {
width: 300px;
height: 300px;
background: red;
margin: auto;
position: relative;
margin-top: 150px;
}
五、table-cell实现水平垂直居中: vertical-align: middle组合使用
.Center {
width: 600px;
height: 600px;
background: red;
display: table-cell;
vertical-align: middle;
text-align: center;
}
.Center-son {
width: 200px;
height: 200px;
background: honeydew;
display: inline-block;
}
六、采用弹性盒子
display: flex;
align-items: center;
justify-content: center;