結(jié)合CSS3的新特性來總結(jié)垂直居中的實(shí)現(xiàn)方法

0.單行內(nèi)容的居中
只考慮單行是最簡單的,無論是否給容器固定高度,只要給容器設(shè)置 line-height 和 height,并使兩值相等,再加上 over-flow: hidden 就可以了
- .middle-demo-1{
- height: 4em;
- line-height: 4em;
- overflow: hidden;
- }
優(yōu)點(diǎn):
(1). 同時支持塊級和內(nèi)聯(lián)極元素
(2). 支持所有瀏覽器
缺點(diǎn):
(1). 只能顯示一行
(2). IE中不支持<img>等的居中
要注意的是:
(1). 使用相對高度定義你的 height 和 line-height
(2). 不想毀了你的布局的話,overflow: hidden 一定要
為什么?
請比較以下兩個例子:
- <p style="background: #900; color: #00f; font: bold 12px/24px Helvertica,Arial,sans-serif; height:24px; width:370px;">Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>
- <br/>
- <br/>
- <p style="background: #090; color: #00f; font: bold 12px/2em Helvertica,Arial,sans-serif; height:2em; width:370px; overflow: hidden;">Lorem ipsum dolor sit amet, consectetuer adipiscing elit.</p>
上一個高度是用的絕對單位px,并且沒有隱藏溢出,下一個高度用的單位是相對單位em,并且隱藏了溢出。如果你的瀏覽器支持放大字體,那么盡情地放大字體,看看會出現(xiàn)什么效果。
1.使用position:absolute(fixed),設(shè)置left、top、margin-left、margin-top的屬性;
- .box{
- position:absolute;/*或fixed*/
- top:50%;
- left:50%;
- margin-top:-100px;
- margin-left:-200px;
- }
2.利用position:fixed(absolute)屬性,margin:auto這個必須不要忘記了;
- .box{
- position: absolute;或fixed
- top:0;
- rightright:0;
- bottombottom:0;
- left:0;
- margin: auto;
- }
3.利用display:table-cell屬性使內(nèi)容垂直居中;
- .box{
- display:table-cell;
- vertical-align:middle;
- text-align:center;
- width:120px;
- height:120px;
- background:purple;
- }
4.使用css3的新屬性transform:translate(x,y)屬性;
- .box{
- position: absolute;
- transform: translate(50%,50%);
- -webkit-transform:translate(50%,50%);
- -moz-transform:translate(50%,50%);
- -ms-transform:translate(50%,50%);
- }
5.最高大上的一種,使用:before元素;
- .box{
- position:fixed;
- display:block;
- background:rgba(0,0,0,.5);
- }
- .box:before{
- content:'';
- display:inline-block;
- vertical-align:middle;
- height:100%;
- }
- .box.content{
- width:60px;
- height:60px;
- line-height:60px;
- color:red;
6.Flex布局;
- .box{
- display: -webkit-box;
- display: -webkit-flex;
- display: -moz-box;
- display: -moz-flex;
- display: -ms-flexbox;
- display: flex;
- 水平居中
- -webkit-box-align: center;
- -moz-box-align: center;
- -ms-flex-pack:center;
- -webkit-justify-content: center;
- -moz-justify-content: center;
- justify-content: center;
- 垂直居中
- -webkit-box-pack: center;
- -moz-box-pack: center;
- -ms-flex-align:center;
- -webkit-align-items: center;
- -moz-align-items: center;
- align-items: center;
- }
相關(guān)文章
利用CSS3的flexbox實(shí)現(xiàn)水平垂直居中與三列等高布局
這篇文章給大家介紹了三個小節(jié)的內(nèi)容,其中包括關(guān)于css3中flexbox需要掌握的概念、flexbox實(shí)現(xiàn)水平垂直居中對齊和三列等高自適應(yīng)頁腳區(qū)域黏附底部的布局,有需要的可以參考2016-09-12css3設(shè)置box-pack和box-align讓div里面的元素垂直居中
只要設(shè)置元素的box-pack和box-align即可,這兩個屬性當(dāng)前只有webkit和moz支持,要設(shè)置垂直居中的話只需要將這兩個屬性的值都設(shè)置為center即可,需要的朋友可以參考下2014-09-01CSS3實(shí)現(xiàn)水平居中、垂直居中、水平垂直居中的實(shí)例代碼
在前端面試中經(jīng)常會遇到css居中效果的實(shí)現(xiàn),今天小編給大家分享幾種css垂直水平居中的方法,通過實(shí)例代碼給大家講解,需要的朋友參考下吧2020-02-27