什么是布局
現(xiàn)有的樣式不能滿足人們的需求朝聋,人們需要更加具體的分區(qū)嗡午,例如:導(dǎo)航欄,內(nèi)容冀痕,廣告欄等等荔睹。
單列布局
實(shí)現(xiàn)方式:固定的寬度和整體居中
width:500px;
margin: 0 auto;
通欄就是從新創(chuàng)建一個(gè)div,將頭部或底部包裹在里面言蛇,添加背景色僻他,設(shè)置合適的高度
雙列布局
實(shí)現(xiàn)方式:一側(cè)固定寬度,一側(cè)自適應(yīng)寬度
<style>
.a{
width: 200px;
height: 400px;
background: red;
float: left;
}
.b{
height: 500px;
margin-left: 210px;
background: blue;
}
</style>
<div class="a"></div>
<div class="b"></div>
三列布局
實(shí)現(xiàn)方式:左右兩側(cè)固定寬度腊尚,中間自適應(yīng)寬度
<style>
.a{
width: 200px;
height: 400px;
background: red;
float: left;
}
.b{
height: 400px;
width: 200px;
background: blue;
float: right;
}
.c{
height: 500px;
background: pink;
margin-left: 210px;
margin-right: 210px;
}
</style>
<div class="a"></div>
<div class="b"></div>
<div class="c"></div>
元素居中
水平居中
行內(nèi)元素居中
text-align:center;
塊級(jí)元素居中
margin: 0 auto;
垂直居中
可以用padding上下相等
padding-top:10px;
padding-bottom:10px;
用絕對(duì)定位實(shí)現(xiàn)居中
width:200px;
height:300px;
position:absolute;
left:50%;
top:50%;
margin-top:150px;
margin-left:100px;
這種方法需要設(shè)置盒子的寬高吨拗,margin-top和margin-left分別是寬高的一半
也有一種不需要設(shè)置寬高的方法,在css3中有一種新屬性是transform:translate(x,y)來實(shí)現(xiàn)居中
position:absolute;
left:50%;
top:50%;
transform:translate(-50%,-50%);
用vertical-align:middle實(shí)現(xiàn)居中
vertical-align 屬性設(shè)置元素的垂直對(duì)齊方式婿斥,但是它的定義是行內(nèi)元素的基線相對(duì)于該元素所在行的基線的垂直對(duì)齊
所以當(dāng)我們想讓圖片也垂直居中時(shí)就要讓圖片也設(shè)置vertical-align:middle
當(dāng)我們明白原理之后劝篷,會(huì)想如何讓文字不占位置呢,可以像下面這樣運(yùn)用偽元素
<div class=“box”>
<img src=“http://.......”>
</div>
<style>
.box{
width: 300px;
height: 200px;
border: 1px solid ;
text-align: center;
}
.box:before{
content:'';
display: inline-block;
height: 100%;
vertical-align: middle;
}
.box img{
vertical-align: middle;
background: blue;
}
</style>
用display:table-cell來實(shí)現(xiàn)居中
<div class=“box”>
<img src=“http://.......”>
</div>
<style>
.box{
width: 300px;
height: 200px;
border: 1px solid ;
display: table-cell;
vertical-align: middle;
text-align: center;
}
</style>
用display:flex來實(shí)現(xiàn)居中
<div class=“box”>
<img src=“http://.......”>
</div>
<style>
.box {
width: 100vw;
height: 100vh; /* 設(shè)置寬高以顯示居中效果 */
display: flex; /* 彈性布局 */
align-items: center; /* 垂直居中 */
justify-content: center; /* 水平居中 */
}
body{
margin: 0;
}
</style>
媒體查詢
一個(gè)媒體查詢由一個(gè)可選的媒體類型和零個(gè)或多個(gè)使用媒體功能的限制了樣式表范圍的表達(dá)式組成民宿,例如寬度娇妓、高度和顏色。媒體查詢活鹰,添加自CSS3峡蟋,允許內(nèi)容的呈現(xiàn)針對(duì)一個(gè)特定范圍的輸出設(shè)備而進(jìn)行裁剪,而不必改變內(nèi)容本身华望。
@media screen and (max-width:900px){
.container{
background: red;
}
}
當(dāng)媒體樂行匹配且表達(dá)式為真時(shí)蕊蝗,對(duì)應(yīng)的style就起其作用,除非使用not或者only操作符赖舟,否則媒體類型不是必須的蓬戚,默認(rèn)代表所有媒體類型
更多了解,請(qǐng)點(diǎn)擊https://developer.mozilla.org/zhCN/docs/Web/Guide/CSS/Media_queries (中文版)
https://developer.mozilla.org/en-US/docs/Web/CSS/@media (英文版)