1. 使用css3的translate水平垂直居中元素
<div class="center">
<div class="center_text">
我是要居中的内容
</div>
</div>
.center {
position: relative;
height: 500px;
}
.center_text{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 300px;
height: 600px;
}
这种方式将脱离文档流的元素,设置top:50%,left:50%,
然后使用transform来向左向上便宜半个内元素的宽和高。
------------------------------------------------------------
//父级别
.progress__bg{
position:relative;
height:10rpx;
width:0%;
font-size:0;
border-radius:6rpx;
background:#26E470;
transition: all ease-in-out 1s;
}
//子级别 垂直居中
.progress__icon{
position: absolute;
right:-34rpx;
top:50%;
width:68rpx;
height:68rpx;
transform: translateY(-50%);
background-image:url('https://elion.oss-cn-beijing.aliyuncs.com/islGame_activity/progress_btn.png');
}
//子级别 水平居中
.progress__count{
position:absolute;
left:50%;
transform: translateX(-50%);
}
2.flex
display:table-cell配合width,text-align:center,vertical-align:middle让大小不固定元素垂直居中,这个方式将要对其的元素设置成为一个td,float、absolute等属性都会影响它的实现,不响应margin属性;
<div class="center">
<div class="center_text">
1111111
</div>
</div>
.center {
display: table;
width: 100%;
}
.center_text {
display: table-cell;
text-align: center;
vertical-align: middle;
}
3.行内元素
把height和line-height的值设置成一样的
4. 使用css3计算的方式居中元素calc
.center {
position: relative;
height: 300px;
width: 1000px;
border: 1px solid #ccc;
}
.center_text{
position: absolute;
top: calc(50% - 50px);
left: calc(50% - 150px);
width: 300px;
height: 100px;
border: 1px solid #000;
}
-------------------------------
.center {
position: relative;
height: 300px;
width: 1000px;
border: 1px solid #ccc;
}
.center_text{
position: absolute;
top: calc(50% - 50px);
left: calc(50% - 150px);
width: 300px;
height: 100px;
border: 1px solid #000;
}
1.
1.
1.
1.
1.