本篇內容主要講解“css中常用的幾種居中方法介紹”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學習“css中常用的幾種居中方法介紹”吧!
今天我們就細數一下幾種方法:
1,使用position:absolute,設置left、top、margin-left、margin-top的屬性
CSS Code復制內容到剪貼板
.one{
position:absolute;
width:200px;
height:200px;
top:50%;
left:50%;
margin-top:-100px;
margin-left:-100px;
background:red;
}
這種方法基本瀏覽器都能夠兼容,不足之處就是需要固定寬高。
2,使用position:fixed,同樣設置left、top、margin-left、margin-top的屬性
CSS Code復制內容到剪貼板
.two{
position:fixed;
width:180px;
height:180px;
top:50%;
left:50%;
margin-top:-90px;
margin-left:-90px;
background:orange;
}
大家都知道的position:fixed,IE是不支持這個屬性的
3,利用position:fixed屬性,margin:auto這個必須不要忘記了。
CSS Code復制內容到剪貼板
.three{
position:fixed;
width:160px;
height:160px;
top:0;
rightright:0;
bottombottom:0;
left:0;
margin:auto;
background:pink;
}
4,利用position:absolute屬性,設置top/bottom/right/left
CSS Code復制內容到剪貼板
.four{
position:absolute;
width:140px;
height:140px;
top:0;
rightright:0;
bottombottom:0;
left:0;
margin:auto;
background:black;
}
5,利用display:table-cell屬性使內容垂直居中
CSS Code復制內容到剪貼板
.five{
display:table-cell;
vertical-align:middle;
text-align:center;
width:120px;
height:120px;
background:purple;
}
6,最簡單的一種使行內元素居中的方法,使用line-height屬性
CSS Code復制內容到剪貼板
.six{
width:100px;
height:100px;
line-height:100px;
text-align:center;
background:gray;
}
這種方法也很實用,比如使文字垂直居中對齊
7,使用css3的display:-webkit-box屬性,再設置-webkit-box-pack:center/-webkit-box-align:center
CSS Code復制內容到剪貼板
.seven{
width:90px;
height:90px;
display:-webkit-box;
-webkit-box-pack:center;
-webkit-box-align:center;
background:yellow;
color:black;
}
8,使用css3的新屬性transform:translate(x,y)屬性
CSS Code復制內容到剪貼板
.eight{
position:absolute;
width:80px;
height:80px;
top:50%;
left:50%;
transform:translate(-50%,-50%);
-webkit-transform:translate(-50%,-50%);
-moz-transform:translate(-50%,-50%);
-ms-transform:translate(-50%,-50%);
background:green;
}
這個方法可以不需要設定固定的寬高,在移動端用的會比較多,在移動端css3兼容的比較好
9、最高大上的一種,使用:before元素
CSS Code復制內容到剪貼板
.nine{
position:fixed;
display:block;
top:0;
rightright:0;
bottombottom:0;
left:0;
text-align:center;
background:rgba(0,0,0,.5);
}
.nine:before{
content:'';
display:inline-block;
vertical-align:middle;
height:100%;
}
.nine .content{
display:inline-block;
vertical-align:middle;
width:60px;
height:60px;
line-height:60px;
color:red;
background:yellow;
}
到此,相信大家對“css中常用的幾種居中方法介紹”有了更深的了解,不妨來實際操作一番吧!這里是億速云網站,更多相關內容可以進入相關頻道進行查詢,關注我們,繼續學習!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。