水平和垂直居中的几种方式

行内元素实现水平垂直居中:

text-align: center;(text-align: center只能实现文本的垂直居中)

line-height: 50px;(line-height不能实现多行文本的垂直居中)

padding:50px;(不固定高度的垂直居中 通过设置padding实现)

使用display设置为table,配合样式vertical-align设置为middle来实现(基线对齐),如下:

父元素{

display:table;

}

子元素{

display:table-cell;

vertical-align:middle;

}

块级元素实现水平垂直居中:

第一种方式:使用弹性盒模型实现水平垂直居中

display: flex;

justify-content: center;

align-items: center;

第二种方式:采取绝对定位配合margin的方式实现(这种方式有缺陷 需要知道固定的宽度和高度才行)

position: absolute;

left:50%;

top:50%;

margin-left: -50px;(高度设置了100px,margin-left就是宽度的一半)

margin-top: -50px;(宽度也设置了100px,margin-top就是高度的一半)

第三种方式:可以采取借助css3的变形属性transform来实现的方式实现

position: absolute;

left:50%;

top:50%;

transform: translate(-50%,-50%);(在当前位置偏移自身宽高的一半)

第四种方式:需要盒子有宽高,但是不需要去计算偏移盒子的宽高

position: absolute;

left:0;

top:0;

right:0;

bottom:0;

margin:auto;

height:100px;

width:100px;
第五种方式:grid(网格布局)

给父级设置:display:grid;

给子元素设置:alig-self:center;

justify-self:center

第六种方法:absolute + calc(计算)

这种方法top的百分比是基于元素的左上角,那么再减去高度和宽度的一半就好

calc:CSS3新增的,任何长度值都可以通过calc()函数进行计算

posted @ 2022-11-07 12:47  LT先生  阅读(513)  评论(0编辑  收藏  举报