水平居中設(shè)置
1、行內(nèi)元素
設(shè)置 text-align:center
2、定寬塊狀元素
設(shè)置 左右 margin 值為 auto
3、不定寬塊狀元素
a:在元素外加入 table 標(biāo)簽(完整的,包括 table、tbody、tr、td),該元素寫在 td 內(nèi),然后設(shè)置 margin 的值為 auto
b:給該元素設(shè)置 displa:inine 方法
c:父元素設(shè)置 position:relative 和 left:50%,子元素設(shè)置 position:relative 和 left:50%
垂直居中設(shè)置
1、父元素高度確定的單行文本
設(shè)置 height = line-height
2、父元素高度確定的多行文本
a:插入 table (插入方法和水平居中一樣),然后設(shè)置 vertical-align:middle
b:先設(shè)置 display:table-cell 再設(shè)置 vertical-align:middle
在前端面試中,大都會問你div居中的方法:
不過以后文筆肯定會變得更好一些的。
開始這些東西之前也可以測試一下你對html了解多少,讓我們測試一下吧,小測驗:你對HTML5了解有多少?
今天就細(xì)數(shù)一下幾種方法:
1,使用position:absolute,設(shè)置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,同樣設(shè)置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屬性,設(shè)置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屬性使內(nèi)容垂直居中
.five{
display:table-cell;
vertical-align:middle;
text-align:center;
width:120px;
height:120px;
background:purple;
}
6,最簡單的一種使行內(nèi)元素居中的方法,使用line-height屬性
.six{
width:100px;
height:100px;
line-height:100px;
text-align:center;
background:gray;
}
這種方法也很實用,比如使文字垂直居中對齊
7,使用css3的display:-webkit-box屬性,再設(shè)置-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;
}
這個方法可以不需要設(shè)定固定的寬高,在移動端用的會比較多,在移動端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;
}
總而言之所有的居中的方法就是你必須要掌握css屬性的這個概念HTML DIV+CSS ,你掌握了就可以好好的運用這些居中的東西了