Skip to main content

如何在不同设备中统一 CSS 样式

例如:针对要显示的页面类型(桌面 PC,笔记本,平板,手机,页面的印刷版本…)

解决方式:利用响应式设计,根据不同设备属性引入不同的 css 样式文件

引入方式:

  • <link>标签
  • CSS 中使用@media 关键字

不同设备属性:

  • 根据设备类型
  • 根据设备宽度
  • 根据设备比例

根据设备类型 例如:打印机设备

<link rel="stylesheet" href="loung-print.css" media="print" />

lounge-print 文件只有在媒体类型为 media 才会使用。说明需要我们要通过打印机查看页面

@media print {
body {
font-family: Times, 'Times New Roman', serif;
}
}

根据设备宽度

<link rel="stylesheet" media="screen and (max-width:600px)" href="small.css" type="text/css" />

当屏幕小于或等于 600px 时,将采用 small.css 样式来渲染 Web 页面

<link rel="stylesheet" media="screen and (min-width:900px)" href="big.css" type="text/css" />

当屏幕大于或等于 900px 时,将采用 big.css 样式来渲染 Web 页面。

body {
background-color: #fff;
}
@media screen and (max-width: 600px) {
body {
background-color: #ccc;
}
}

当屏幕小于或等于 600px 时,背景色显示成灰色。

body {
background-color: #fff;
}
@media screen and (min-width: 900px) {
body {
background-color: #ccc;
}
}

当屏幕大于或等于 900px 时,背景色显示成灰色。

根据设备比例

<link rel="stylesheet" media="screen and (device-aspect-ratio:16/9)" href="small.css" type="text/css" />

当屏幕比例为 16:9 时,将采用 small.css 样式来渲染 Web 页面

@media only screen and (device-aspect-ratio: 411/823) {
.beijing1 {
background-color: #000000;
}
}