CSS垂直居中和水平垂直居中

盒子垂直居中的方法

1.img的垂直居中 
{
    display:table-cell;
    text-align:center;
    vertical-align:middle;
}
2.重写容器的align-items属性
.father{display:flex}
.son{align-self:center}
写在弹性容器内子元素上的align-self可以重写容器的align-items属性,可取得值与align-items一样。
3.可以通过tranform实现垂直居中
1)已知父元素高度
.son{
position:relative;
top:50%;
transform:translateY(-50%)
}
2)未知父元素高度
设置子绝父相,其他与已知父元素一样

4.文本的垂直居中
line-height 设置为那个对象的 height 
.content{height: 100px;line-height: 100px;}

盒子水平垂直居中的方法

父子宽高都有:

方法一、利用margin:auto;设置子绝父相,子元素margin:auto,上下左右全给0;

方法二、利用transform;设置子绝父相,子:top:50%;left:50%;transform:translite(-50%,-50%);

方法三、利用定位;子绝父相,top和left都为50%,margin-top和margin-left都为子元素宽度的负一半

没有宽高实现方法:

方法四、利用弹性布局;只给父元素设置display:flex;justify-content:center;align-items:center;

方法五、利用display:table-cell;父元素设置display:table-cell ; vertical-align:middle ; text-align:center ; 子元素转换为行内块

方法一)利用margin:auto
.parent {
width: 500px;
height: 500px;
position: relative;
}
.child {
width: 100px;
height: 100px;
position: absolute;
margin:auto;
top:0;
left:0;
right:0;
bottom:0;
}
方法二)利用transform
.parent{
width:500px;
height:500px;
position:relative;
}
.child{
width:100px;
height:100px;
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%)
}
方法三)利用定位
.parent {
width: 500px;
height: 500px;
position: relative;
}
.child {
width: 100px;
height: 100px;
position: absolute;
top:50%;
left:50%;
margin-top:-50px;
margin-left:-50px;
}
方法四)利用弹性布局
.parent{
width:500px;
height:500px;
display:flex;
justify-content:center;
align-items:center
}
.child{
width:100px;
height:100px;
}
方法五)利用display:table-cell
.parent{
width:500px;
height:500px;
display:table-cell;
vertical-align:middle;
text-align:center;
}
.child{
width:100px;
height:100px;
display:inline-block;
}
posted @ 2021-11-15 21:51  安逸cosmos  阅读(62)  评论(0)    收藏  举报