CSS媒體查詢使您能夠格式化文檔,以在不同大小的輸出設(shè)備上正確顯示。
媒體查詢使您可以針對(duì)特定范圍的設(shè)備(例如手機(jī),平板電腦,臺(tái)式機(jī)等)自定義網(wǎng)頁(yè)的顯示方式,而無(wú)需更改標(biāo)記。媒體查詢由媒體類型和零個(gè)或多個(gè)與特定媒體功能(例如設(shè)備寬度或屏幕分辨率)的條件匹配的表達(dá)式組成。
由于媒體查詢是邏輯表達(dá)式,因此可以解析為true或false。如果在媒體查詢中指定的媒體類型與正在顯示文檔的設(shè)備類型匹配,并且滿足媒體查詢中的所有表達(dá)式,則查詢結(jié)果為true。當(dāng)媒體查詢?yōu)閠rue時(shí),相關(guān)的樣式表或樣式規(guī)則將應(yīng)用于目標(biāo)設(shè)備。這是標(biāo)準(zhǔn)設(shè)備媒體查詢的簡(jiǎn)單示例。
/* Smartphones (portrait and landscape) ---------- */
@media screen and (min-width: 320px) and (max-width: 480px){
/* styles */
}
/* Smartphones (portrait) ---------- */
@media screen and (max-width: 320px){
/* styles */
}
/* Smartphones (landscape) ---------- */
@media screen and (min-width: 321px){
/* styles */
}
/* Tablets, iPads (portrait and landscape) ---------- */
@media screen and (min-width: 768px) and (max-width: 1024px){
/* styles */
}
/* Tablets, iPads (portrait) ---------- */
@media screen and (min-width: 768px){
/* styles */
}
/* Tablets, iPads (landscape) ---------- */
@media screen and (min-width: 1024px){
/* styles */
}
/* Desktops and laptops ---------- */
@media screen and (min-width: 1224px){
/* styles */
}
/* Large screens ---------- */
@media screen and (min-width: 1824px){
/* styles */
}測(cè)試看看?/?提示:媒體查詢是創(chuàng)建響應(yīng)式布局的絕佳方法。使用媒體查詢,您可以為用戶在智能手機(jī)或平板電腦等設(shè)備上瀏覽而不同地自定義網(wǎng)站,而無(wú)需更改頁(yè)面的實(shí)際內(nèi)容。
您可以使用CSS媒體查詢來(lái)更改網(wǎng)頁(yè)寬度和相關(guān)元素,以在不同設(shè)備上為用戶提供最佳的觀看體驗(yàn)。
以下樣式規(guī)則將根據(jù)屏幕或視口大小自動(dòng)更改容器元素的寬度。例如,如果視口寬度小于768像素,它將覆蓋視口寬度的100%,如果它大于768像素但小于1024像素,則將為750像素,依此類推。
.container {
margin: 0 auto;
background: #f2f2f2;
box-sizing: border-box;
}
/* Mobile phones (portrait and landscape) ---------- */
@media screen and (max-width: 767px){
.container {
width: 100%;
padding: 0 10px;
}
}
/* Tablets and iPads (portrait and landscape) ---------- */
@media screen and (min-width: 768px) and (max-width: 1023px){
.container {
width: 750px;
padding: 0 10px;
}
}
/* Low resolution desktops and laptops ---------- */
@media screen and (min-width: 1024px) {
.container {
width: 980px;
padding: 0 15px;
}
}
/* High resolution desktops and laptops ---------- */
@media screen and (min-width: 1280px) {
.container {
width: 1200px;
padding: 0 20px;
}
}測(cè)試看看?/?注意:可以在元素上使用CSS3 框大小調(diào)整屬性,以更輕松地創(chuàng)建更直觀,更靈活的布局。
您還可以使用CSS媒體查詢來(lái)使您的多列網(wǎng)站布局更具適應(yīng)性,并且只需很少的自定義即可響應(yīng)設(shè)備。
如果視口大小大于或等于768像素,則以下樣式規(guī)則將創(chuàng)建兩列布局,但如果小于或等于768像素,它將被呈現(xiàn)為一列布局。
.column {
width: 48%;
padding: 0 15px;
box-sizing: border-box;
background: #93dcff;
float: left;
}
.container .column:first-child{
margin-right: 4%;
}
@media screen and (max-width: 767px){
.column {
width: 100%;
padding: 5px 20px;
float: none;
}
.container .column:first-child{
margin-right: 0;
margin-bottom: 20px;
}
}測(cè)試看看?/?