一、利用绝对定位居中
方法:利用 position: absolute; 相对于父级元素进行绝对定位,对 top 、left 、right 、bottom 等的值进行操控来实现。具体代码如下所示:
1、margin: auto; 方法
{
width: 100px;
height: 100px;
border: 1px solid green;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
margin: auto;
}
2、改变 margin 值
<div class="body" >
<div class="center" ></div>
</div>
.body{
width: 500px;
height: 500px;
border: 1px solid #000;
position: relatuve;
}
.center{
width: 100px;
height: 100px;
border: 1px solid green;
position: absolute;
top: 50%;
left: 50%;
margin-top: -50px;
margin-left: -50px;
}
二、利用弹性盒子居中
方法:元素 display 定义为 flex 。利用 fiexd 容器和容器内项目 item 的关系属性进行垂直居中。具体代码如下:
1、容器直接让项目垂直居中
<div class="body" >
<div class="content"></div>
</div>
.body{
width: 500px;
height: 500px;
border: 1px solid red;
display: flex;
justify-content: center;
align-items: center;
}
.content{
width: 100px;
height: 100px;
border: 1px solid green;
}
2、容器先让项目水平居中,项目自身要求居中
<div class="body" >
<div class="content" ></div>
</div>
.body{
width: 500px;
height: 500px;
border: 1px solid red;
display: flex;
justify-content: center;
}
.content{
width: 100px;
height: 100px;
border: 1px solid green;
align-self: center;
}
三、利用行高对文本垂直居中
方法:设置文本 line-height 值和容器高度一致,然后 text-align: center; 具体代码如下:
<div class="inText" >
我的猫猫叫粪球
</div>
.inText{
width: 500px;
height: 300px;
line-height: 300px;
text-align: center;
}