CSS媒體類型詳細介紹
作者:管理員 來源:互聯網 發布時間:2025-12-11 10:30:16 點擊數:0
一、什么是媒體類型
CSS媒體類型(Media Types)是CSS2規范中定義的,用于指定樣式表針對的輸出設備類型。它們允許開發者針對不同的設備或媒體類型應用不同的樣式規則。
二、主要媒體類型列表
1. all
適用于所有設備
@media all {
body { font-family: Arial, sans-serif; }
}
2. screen
主要用于彩色計算機屏幕(最常用)
@media screen {
body { background-color: #f5f5f5; }
}3. print
用于打印和打印預覽
@media print {
/* 打印時隱藏不必要的元素 */
.advertisement, .sidebar { display: none; }
/* 設置打印顏色和字體 */
body { color: black; font-size: 12pt; }
/* 確保鏈接在打印時顯示URL */
a:after { content: " (" attr(href) ")"; }
}4. speech
適用于語音合成器、屏幕閱讀器等發聲設備
@media speech {
/* 為屏幕閱讀器提供更好的體驗 */
.visually-hidden {
clip-path: none !important;
position: static !important;
}
}5. 其他歷史媒體類型(已廢棄或不常用)

三、使用方法
1. 在link標簽中使用
<link rel="stylesheet" media="screen" href="screen.css"> <link rel="stylesheet" media="print" href="print.css"> <link rel="stylesheet" media="screen, print" href="common.css">
2. 在CSS中使用@import
@import url("screen.css") screen;
@import url("print.css") print;3. 在CSS中使用@media規則
/* 基本用法 */
@media screen {
body { font-size: 16px; }
}
@media print {
body { font-size: 12pt; }
}
/* 同時指定多個媒體類型 */
@media screen, print {
h1 { color: #333; }
}四、媒體類型與媒體查詢
CSS3引入了媒體查詢(Media Queries),擴展了媒體類型的功能,使其更加強大和實用:
/* CSS2的媒體類型 */
@media screen { ... }
/* CSS3的媒體查詢 - 更精細的控制 */
@media screen and (min-width: 768px) { ... }
@media screen and (max-width: 767px) and (orientation: portrait) { ... }五、實際應用示例
打印樣式設計
/* 打印樣式表 */
@media print {
* {
background: transparent !important;
color: #000 !important;
text-shadow: none !important;
}
/* 調整布局 */
body {
width: 100% !important;
margin: 0 !important;
padding: 0 !important;
}
/* 隱藏不必要的內容 */
nav, .sidebar, .ad-banner, .social-share {
display: none !important;
}
/* 優化打印分頁 */
h1, h2, h3, h4 {
page-break-after: avoid;
}
img, table, figure {
page-break-inside: avoid;
}
/* 顯示鏈接URL */
a {
text-decoration: underline;
}
a[href^="http"]:after {
content: " (" attr(href) ")";
}
/* 打印頁眉頁腳 */
@page {
margin: 2cm;
@top-center {
content: "文檔標題";
}
@bottom-right {
content: counter(page);
}
}
}針對屏幕閱讀器的優化
@media speech {
/* 隱藏純視覺裝飾 */
.icon:before {
content: "" !important;
}
/* 為屏幕閱讀器提供更清晰的結構 */
.visually-hidden {
clip-path: none;
position: static;
width: auto;
height: auto;
margin: 0;
}
/* 控制語音屬性 */
.important {
voice-pitch: high;
voice-rate: slow;
}
.aside {
voice-family: female;
voice-pitch: medium;
}
}六、最佳實踐
始終包含print媒體類型:為網站創建打印友好的版本
使用邏輯運算符組合條件:
@media only screen and (min-width: 320px) and (max-width: 767px) { ... }"only"關鍵字:用于隱藏舊瀏覽器中的樣式表
@media only screen and (min-width: 768px) { ... }移動優先設計:
/* 基礎樣式 - 移動設備 */
body { font-size: 14px; }
/* 平板設備 */
@media screen and (min-width: 768px) {
body { font-size: 16px; }
}
/* 桌面設備 */
@media screen and (min-width: 1024px) {
body { font-size: 18px; }
}七、瀏覽器支持
所有現代瀏覽器都支持主要的媒體類型(all, screen, print)
speech媒體類型支持有限,主要與屏幕閱讀器相關
廢棄的媒體類型(如handheld)在現代瀏覽器中可能不被識別
上一篇:網站設計:首頁要不要“塞滿”?
相關內容:
