html结构如下:
<div class="container">
<div class="item" style="width: 100px; height: 100px; background: #999;">
块状元素
</div>
</div>
<div class="container">
<div class="item">不定高宽的块状元素</div>
</div>
<div class="container">
<span class="item">行内元素</span>
</div>
其中,container样式为:
.container {
height: 200px;
width: 200px;
margin-bottom: 10px;
background-color: red;
}
实现item在自己的父容器container中水平垂直居中
法一:父flex+主轴+交叉轴
.container {
/* 法一:flex 主轴 交叉轴 */
display: flex;
justify-content: center;
align-items: center;
}
法二:父flex+子margin:auto
.container {
display: flex;
}
.item{
margin: auto;
}
法三:父相+子绝+top/left:50%+translate:-50%
.container{
position: relative;
}
.item {
position: absolute;
top:50%;
left:50%;
/* 宽高已知未知均可 */
transform:translate(-50%,-50%);
}
法四:父相+子绝+top/left:50%+margin-top/left:负宽高的一半
.container{
position: relative;
}
.item {
position: absolute;
top:50%;
left:50%;
/* 已知宽高 */
margin-top: -50px;
margin-left: -50px;
}
法五:父相+子绝+top/left/right/bottom:0+margin:auto
.container{
position: relative;
}
.item {
position: absolute;
/* 已知宽高 */
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
另外:行内元素设置水平垂直居中可以写成:
span{
text-align: center;
line-height: 200px;
}
好像还有grid可以实现,但是目前还不会,哈哈哈,以后再说。。。