日韩黑丝制服一区视频播放|日韩欧美人妻丝袜视频在线观看|九九影院一级蜜桃|亚洲中文在线导航|青草草视频在线观看|婷婷五月色伊人网站|日本一区二区在线|国产AV一二三四区毛片|正在播放久草视频|亚洲色图精品一区

分享

純CSS實現(xiàn)垂直居中的幾種方法

 昵稱57256554 2018-07-24

垂直居中是布局中十分常見的效果之一,為實現(xiàn)良好的兼容性,PC端實現(xiàn)垂直居中的方法一般是通過絕對定位,table-cell,負邊距等方法。有了css3,針對移動端的垂直居中就更加多樣化。

方法1:table-cell

html結(jié)構(gòu):

1
2
3
<div class="box box1">
        <span>垂直居中</span>
</div>

css:

1
2
3
4
5
.box1{
    display: table-cell;
    vertical-align: middle;
    text-align: center;        
}

方法2:display:flex

1
2
3
4
5
.box2{
    display: flex;
    justify-content:center;
    align-items:Center;
}

方法3:絕對定位和負邊距

復(fù)制代碼
.box3{position:relative;}
.box3 span{ position: absolute; width:100px; height: 50px; top:50%; left:50%; margin-left:-50px; margin-top:-25px; text-align: center; }
復(fù)制代碼

方法4:絕對定位和0

1
2
3
4
5
6
7
8
9
.box4 span{
  width: 50%; 
  height: 50%; 
  background: #000;
  overflow: auto; 
  margin: auto; 
  position: absolute; 
  top: 0; left: 0; bottom: 0; right: 0; 
}

這種方法跟上面的有些類似,但是這里是通過margin:auto和top,left,right,bottom都設(shè)置為0實現(xiàn)居中,很神奇吧。不過這里得確定內(nèi)部元素的高度,可以用百分比,比較適合移動端。

方法5:translate

1
2
3
4
5
6
7
8
.box6 span{
            position: absolute;
            top:50%;
            left:50%;
            width:100%;
            transform:translate(-50%,-50%);
            text-align: center;
        }

這實際上是方法3的變形,移位是通過translate來實現(xiàn)的。

方法6:display:inline-block

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
.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;
}

這種方法確實巧妙...通過:after來占位。

方法7:display:flex和margin:auto

1
2
3
4
5
.box8{
    display: flex;
    text-align: center;
}
.box8 span{margin: auto;}

方法8:display:-webkit-box

復(fù)制代碼
.box9{
    display: -webkit-box;
    -webkit-box-pack:center;
    -webkit-box-align:center;
    -webkit-box-orient: vertical;
    text-align: center
}
復(fù)制代碼

css3博大精深,可以實現(xiàn)很多創(chuàng)造性的效果,需要好好研究下。

今天又發(fā)現(xiàn)一種方法,現(xiàn)在補上:

方法9:display:-webkit-box

這種方法,在 content 元素外插入一個 div。設(shè)置此 div height:50%; margin-bottom:-contentheight;。

content 清除浮動,并顯示在中間。

<div class="floater"></div>  
<div class="content"> Content here </div>  
復(fù)制代碼
.floater {
    float:left; 
    height:50%; 
    margin-bottom:-120px;
}
.content {
    clear:both; 
    height:240px; 
    position:relative;
}
復(fù)制代碼

優(yōu)點: 
適用于所有瀏覽器 
沒有足夠空間時(例如:窗口縮小) content 不會被截斷,滾動條出現(xiàn)

缺點: 
唯一我能想到的就是需要額外的空元素了(也沒那么糟,又是另外一個話題)

 

    本站是提供個人知識管理的網(wǎng)絡(luò)存儲空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點。請注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請點擊一鍵舉報。
    轉(zhuǎn)藏 分享 獻花(0

    0條評論

    發(fā)表

    請遵守用戶 評論公約

    類似文章 更多