CSS 媒体类型学习笔记

CSS 媒体查询是一种基于媒体类型和其他条件的动态样式表加载机制,它能够判断设备的参数以及展示方式,并根据这些信息加载不同的样式表文件。这项技术已经被广泛用于移动设备和响应式设计。以下是一些常见的媒体类型。

媒体类型

all

适用于所有设备。

cssCopy Code
@media all { /* Your styles here */ }

print

适用于打印输出设备。

cssCopy Code
@media print { /* Your styles here */ }

screen

适用于计算机屏幕、平板电脑和智能手机等设备。

cssCopy Code
@media screen { /* Your styles here */ }

媒体特征

width 和 height

根据设备的屏幕宽度和高度来加载不同的样式表文件。

cssCopy Code
@media (max-width: 767px) { /* Your styles here */ } @media (min-width: 768px) and (max-width: 991px) { /* Your styles here */ } @media (min-width: 992px) { /* Your styles here */ }

orientation

根据设备的方向来加载不同的样式表文件。

cssCopy Code
@media (orientation: portrait) { /* Your styles here */ } @media (orientation: landscape) { /* Your styles here */ }

resolution

根据设备的分辨率来加载不同的样式表文件。

cssCopy Code
@media (min-resolution: 300dpi) { /* Your styles here */ } @media (max-resolution: 299dpi) { /* Your styles here */ }

aspect-ratio

根据设备的宽高比来加载不同的样式表文件。

cssCopy Code
@media (aspect-ratio: 16/9) { /* Your styles here */ } @media (aspect-ratio: 4/3) { /* Your styles here */ }

实例

下面是一个简单的实例,它会在屏幕宽度小于等于 767 像素和大于等于 768 像素时,分别加载不同的样式表文件。

cssCopy Code
/* 样式表文件:"example.css" */ /* Default styles */ @media (max-width: 767px) { /* Styles for devices with width less than or equal to 767px */ } @media (min-width: 768px) { /* Styles for devices with width greater than or equal to 768px */ }

在 HTML 文件中,我们可以使用以下代码来加载这些样式表文件:

htmlCopy Code
<!-- 加载符合所有媒体类型的样式表文件 --> <link rel="stylesheet" href="example.css" /> <!-- 加载适用于小屏幕设备的样式表文件 --> <link rel="stylesheet" media="(max-width: 767px)" href="example.css" /> <!-- 加载适用于大屏幕设备的样式表文件 --> <link rel="stylesheet" media="(min-width: 768px)" href="example.css" />

通过使用媒体类型和媒体特征,我们可以轻松地实现响应式设计,使得页面在不同的设备和屏幕尺寸下都能够得到良好的展示效果。