引用外部樣式使用link
你可能想針對將要顯示頁面的設備類型(桌面PC、筆記本電腦、平板電腦、手機或者甚至頁面的印刷版本)來調整頁面的樣式,可以利用一個media屬性,
在<link>元素中增加這個屬性,只使用適用於指定設備的樣式文件。
<link href="..." rel="stylesheet" media="screen and (max-device-width=480px)" />
<link href="..." rel="stylesheet" media="print" />
查詢中有很多屬性可以使用,如依賴設備實際屏幕的大小(min-device-width、max-device-width),使用瀏覽器窗口大小(max-width、min-width),以及顯示方向[ orientation,這個可以時橫向(landscape)或縱向(portrait)],
此外還有很多其他的屬性。可以根據需要為html增加多個<link>標記,涵蓋你要支持的所有設備。
在css中增加媒體查詢
要為CSS指定有特定屬性的設備,還有一種方法:不是在link標記中使用媒體查詢,還可以直接寫在CSS中。
采用這種方式,@media規則中只包含特定於中媒體類型的CSS規則。在CSS文件中,要把對所有媒體類型都通用的規則放在@media規則下面,
這樣一來,就不會不必要的重復規則了。另外瀏覽器加載頁面時,它會通過媒體類型來確定頁面適用的規則,而將不匹配的規則忽略。
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title></title> <link href="static/css/test.css" rel="stylesheet" media="screen and (min-width:1024px)" /> <link href="static/css/test.css" rel="stylesheet" media="screen and (max-width:1024px)" /> </head> <body> <div class="div_test"> hello world!!! </div> </body> </html>
test.css樣式文件:
@media screen and (min-width:1024px)
{
.div_test{
font-size:50px;
font-family:'Times New Roman';
font-style:oblique;
color: #000000;
background-color: #808080;
margin:30px;
padding:50px;
padding-left:100px;
border: dashed 1px #0cf60a;
border-radius:5px;
}
}
@media screen and (max-width:900px)
{
.div_test{
font-size:50px;
font-style:oblique;
background-color: #b6ff00;
margin:30px;
padding:50px;
padding-left:100px;
border: double 1px #0cf60a;
border-radius:5px;
}
}