您好,登錄后才能下訂單哦!
本篇文章給大家分享的是有關(guān)CSS中實(shí)現(xiàn)垂直居中的方法有哪些,小編覺得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。
方法1:table-cell
html結(jié)構(gòu):
XML/HTML Code復(fù)制內(nèi)容到剪貼板
<div class="box box1">
<span>垂直居中</span>
</div>
css:
CSS Code復(fù)制內(nèi)容到剪貼板
.box1{
display: table-cell;
vertical-align: middle;
text-align: center;
}
方法2:display:flex
CSS Code復(fù)制內(nèi)容到剪貼板
.box2{
display: flex;
justify-content:center;
align-items:Center;
}
方法3:絕對定位和負(fù)邊距
CSS Code復(fù)制內(nèi)容到剪貼板
.box3{position:relative;}
.box3 span{
position: absolute;
width:100px;
height: 50px;
top:50%;
left:50%;
margin-left:-50px;
margin-top:-25px;
text-align: center;
}
方法4:絕對定位和0
CSS Code復(fù)制內(nèi)容到剪貼板
.box4 span{
width: 50%;
height: 50%;
background: #000;
overflow: auto;
margin: auto;
position: absolute;
top: 0; left: 0; bottombottom: 0; rightright: 0;
}
這種方法跟上面的有些類似,但是這里是通過margin:auto和top,left,right,bottom都設(shè)置為0實(shí)現(xiàn)居中,很神奇吧。不過這里得確定內(nèi)部元素的高度,可以用百分比,比較適合移動(dòng)端。
方法5:translate
CSS Code復(fù)制內(nèi)容到剪貼板
.box6 span{
position: absolute;
top:50%;
left:50%;
width:100%;
transform:translate(-50%,-50%);
text-align: center;
}
這實(shí)際上是方法3的變形,移位是通過translate來實(shí)現(xiàn)的。
方法6:display:inline-block
CSS Code復(fù)制內(nèi)容到剪貼板
.box7{
text-align:center;
font-size:0;
}
.box7 span{
vertical-align:middle;
display:inline-block;
font-size:16px;
}
.box7:after{
content:'';
width:0;
height:100%;
display:inline-block;
vertical-align:middle;
}
這種方法確實(shí)巧妙...通過:after來占位。
方法7:display:flex和margin:auto
CSS Code復(fù)制內(nèi)容到剪貼板
.box8{
display: flex;
text-align: center;
}
.box8 span{margin: auto;}
方法8:display:-webkit-box
CSS Code復(fù)制內(nèi)容到剪貼板
.box9{
display: -webkit-box;
-webkit-box-pack:center;
-webkit-box-align:center;
-webkit-box-orient: vertical;
text-align: center
}
css3博大精深,可以實(shí)現(xiàn)很多創(chuàng)造性的效果,需要好好研究下。
今天又發(fā)現(xiàn)一種方法,現(xiàn)在補(bǔ)上:
方法9:display:-webkit-box
這種方法,在 content 元素外插入一個(gè) div。設(shè)置此 div height:50%; margin-bottom:-contentheight;。
content 清除浮動(dòng),并顯示在中間。
XML/HTML Code復(fù)制內(nèi)容到剪貼板
<div class="floater"></div>
<div class="content"> Content here </div>
CSS Code復(fù)制內(nèi)容到剪貼板
.floater {
float:left;
height:50%;
margin-bottom:-120px;
}
.content {
clear:both;
height:240px;
position:relative;
}
優(yōu)點(diǎn):
適用于所有瀏覽器
沒有足夠空間時(shí)(例如:窗口縮小) content 不會(huì)被截?cái)?,滾動(dòng)條出現(xiàn)
缺點(diǎn):
唯一我能想到的就是需要額外的空元素了
以上就是CSS中實(shí)現(xiàn)垂直居中的方法有哪些,小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見到或用到的。希望你能通過這篇文章學(xué)到更多知識(shí)。更多詳情敬請關(guān)注億速云行業(yè)資訊頻道。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。