1、垂直居中
//css
.vertical{
writing-mode: vertical-lr;
text-align: center;
}
.text{
writing-mode:initial;
}
//html
<div class="vertical">
<span class="text">this is a test</span>
</div>
2、水平居中
//css
.horizontal{
width:200px;
height:200px;
margin:0 auto;
}
//html
<div class="horizontal"></div>
3、垂直水平居中
方法1:使用绝对定位
//css
.center-wrap{
position:relative;
}
.center{
position:absolute;
top:50%;
left:50%;
transform:translate(-50%,-50%);
}
//若已知宽高,也可用.center-alternative-one或者.center-alternative-two替换.center
.center-alternative-one{
width:200px;
height:200px;
position:absolute;
top:calc(50% - 100px);
left:calc(50% - 100px);
}
.center-alternative-two{
width:200px;
height:200px;
position:absolute;
top:50%;
left:50%;
margin-left:-100px;
margin-top:-100px;
}
//html
<div class="center-wrap">
<div class="center"></div>
</div>
方法二:使用display:flex
//css
.center-wrap{
display:flex;
align-items: center;
justify-content: center;
}
//html
<div class="center-wrap">
<div>this is the box which need be setted</div>
</div>
扩展1:
若多个元素需要进行垂直居中,用以下方法可以减少DOM元素的使用:
//css
.box {
width: 300px;
height: 300px;
margin: 0 auto;
border: 1px solid;
display: -webkit-flex;
display: flex; /* 此处是关键*/
-webkit-justify-content: center;
justify-content: center; /* 此处是关键*/
-webkit-align-items: center;
align-items: center; /* 此处是关键*/
-webkit-flex-direction: column;
flex-direction: column; /* 此处是关键*/
}
.title {
font-size: 14px;
font-weight: normal;
}
.img {
width: 200px;
margin: 20px 0;
}
.btn {
width: 100px;
height: 28px;
color: #fc6537;
border-radius: 5px;
border: 1px solid #fc6537;
background-color: #fff;
}
//html
<div class="box">
<hl class="title">多个元素相对于父元素垂直居中</hl>
<img class="img" src="images/flex-direction.jpg" />
<button class="btn">click me</button>
</div>
网友评论