響應式網頁看起來高大上,但實際上,不用JS只用CSS也能實現響應式網站的布局
要用到的就是CSS中的媒體查詢下面來簡單介紹一下怎么運用
使用@media 的三種方式
第一: 直接在CSS文件中使用
@media 類型 and (條件1) and (條件二)
{
css樣式
}
@media screen and (max-width:980px ) {
body{
background-color: red;
}
}
第二:使用@import導入
@import url("css/moxie.css") all and (max-width:980px);
第三,也是最常用的:使用link連接,media屬性用於設置查詢方式
<link rel="stylesheet" type="text/css" href="css/moxie.css" media=“all and (max-width=980px)”/>
我們只需用到width衍生出的max-width這個屬性,定義輸出設備中的頁面可見區域寬度來控制該改變的樣式即可。
下面是一個簡單響應式的布局的html代碼
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>響應式布局</title> <meta name="viewport"content="width=device-width,initial-scale=1.0,maximum-scale=1,user-scalable=no" /> <meta name="format-detection" content="telephone=no,email=no"/> <link rel="stylesheet" type="text/css" href="css/mo2.css"/> </head> <body> <div> <header id="head"> <ul> <li>header1</li> <li>header2</li> <li>header2</li> <li>header2</li> <li>header2</li> </ul> <div>icon</div> </header> <section id="main"> <div class="left"> left </div> <div class="center"> center </div> <div class="right"> right </div> </section> <footer id="foot"> footer </footer> </div> </body> </html>
下邊是CSS樣式
*{ margin: 0px; padding: 0px; font-family: "微軟雅黑"; } #head, #foot, #main { height: 100px; width: 1200px; /*width: 85%;*/ background-color: goldenrod; text-align: center; font-size: 48px; line-height: 100px; margin: 0 auto; } #head div{ display: none; font-size: 20px; height: 30px; width: 100px; background-color: green; float: right; line-height: 30px; margin-top: 35px; } #head ul{ width: 80%; } #head ul li{ width: 20%; float: left; text-align: center; list-style: none;font-size: 20px; } #main{ height: auto; margin: 10px auto; overflow: hidden; } .left, .center, .right{ height: 600px; line-height: 600px; float: left; width: 20%; background-color: red } .center{ width: 60%; border-left: 10px solid #FFF; border-right: 10px solid #FFF; box-sizing: border-box; } @media only screen and (max-width: 1200px) { #head, #foot, #main{ width: 100%; } } @media only screen and (max-width: 980px) { .right{ display: none; } .left{ width: 30%; } .center{ width: 70%; border-right: hidden; } } @media only screen and (max-width: 640px) { .left, .center, .right{ width: 100%; display: block; height: 200px; line-height: 200px; } .center{ border: hidden; border-top: 10px solid #FFFFFF; border-bottom: 10px solid #FFFFFF; height: 600px; line-height: 600px; } #head ul{ display: none; } #head div{ display: block; } }
窗口大於1200px時顯示的樣子
窗口小於1200大於980時,只會被壓縮,並不會發生其他變化
當大於640小於980時,右側欄隱藏
當小於640時,導航欄折疊,body三部分豎直排列顯示,若窗口持續縮小,不在發生變化,區域被壓縮
好了,布局就這么簡單,細節的把握還靠不斷地練習。