2024年5月11日发(作者:)

使用CSS定位元素实现水平垂直居中效果

###一、CSS定位元素水平垂直居中

CSS的定位技术可以实现元素的水平垂直居中显示。主要利用

position属性,定义元素的绝对定位、相对定位或固定定位(fixed),

结合margin或transform两个属性,实现元素的水平垂直居中定位,使

元素能够正中显示。

####1、使用绝对定位:

```css

div

position:absolute;

left:50%;

top:50%;

transform:translate(-50%,-50%);

```

通过绝对定位,position定义了当前元素的定位方式,设置

left:50%,top:50%的值,表示向左右和上下移动50%的距离,再结合

transform:translate(-50%,-50%)的属性,表示元素移动相应的距离,使

得当前元素的位置正好可以居中显示。

####2、使用相对定位:

```css

div

position:relative;

margin:auto;

```

使用相对定位,position定义了当前元素的定位方式,通过margin

设置auto值,表示元素的上下、左右的margin值都设置为auto,让浏

览器自动计算margin值,使得元素正好水平居中显示,也可以设置both

值,让浏览器自动分配上下左右的margin值,从而达到居中的效果。

#### 3、使用flexbox配合margin实现垂直水平居中:

```css

div

display: flex;

justify-content: center;

align-items: center;

margin: auto;

```

使用flexbox配合margin可以较为简单地实现元素的水平垂直居中,

display设置flex,示当前元素使用弹性布局,justify-content定义了

水平方向上的对齐方式,设置为center,示元素水平居中;align-items

定义了垂直方向上的对齐方式,设置为center。