標籤:body strong for pre 寬高 文本 設定 back 方案
一:水平置中方案:
1、行內元素
設定 text-align:center
2、定寬塊狀元素
設定 左右 margin 值為 auto
3、不定寬塊狀元素
a:在元素外加入 table 標籤(完整的,包括 table、tbody、tr、td),該元素寫在 td 內,然後設定 margin 的值為 auto
b:給該元素設定 displa:inine 方法
c:父元素設定 position:relative 和 left:50%,子項目設定 position:relative 和 left:50%
二:垂直置中設定
1、父元素高度確定的單行文本
設定 height = line-height
2、父元素高度確定的多行文本
a:插入 table (插入方法和水平置中一樣),然後設定 vertical-align:middle
b:先設定 display:table-cell 再設定 vertical-align:middle
三:細數一下幾種方法:
1,使用position:absolute,設定left、top、margin-left、margin-top的屬性
.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的屬性
.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這個必須不要忘記了。
.three{ position:fixed; width:160px; height:160px; top:0; right:0; bottom:0; left:0; margin:auto; background:pink;}
4,利用position:absolute屬性,設定top/bottom/right/left
.four{ position:absolute; width:140px; height:140px; top:0; right:0; bottom:0; left:0; margin:auto; background:black;}
5,利用display:table-cell屬性使內容垂直置中
.five{ display:table-cell; vertical-align:middle; text-align:center; width:120px; height:120px; background:purple;}
6,最簡單的一種使行內元素置中的方法,使用line-height屬性
.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
.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)屬性
.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元素
.nine{ position:fixed; display:block; top:0; right:0; bottom: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;}
連結:https://www.zhihu.com/question/20543196/answer/89218605
來源:知乎
CSS置中的方法