Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> CSS

Media Queries với CSS3

Giới thiệu

Media Queries là tính năng CSS3 cho phép áp dụng style tùy theo đặc điểm thiết bị đầu ra (màn hình, in ấn, speech, v.v.). Đây là công cụ cốt lõi để xây dựng giao diện responsive.

Cú pháp

@media [<media-type>] [and|not|only|,] <media-condition> {
  /* CSS rules */
}

Ví dụ cơ bản: Thay đổi background theo màn hình

<!DOCTYPE html>
<html>
<head>
  <style>
    body {
      background-color: lightpink;
      font-family: system-ui, sans-serif;
      padding: 2rem;
      transition: background-color 0.3s ease;
    }
    
    @media screen and (max-width: 420px) {
      body { background-color: lightblue; }
    }
  </style>
</head>
<body>
  <p>Màn hình ≤ 420px: nền xanh nhạt | > 420px: nền hồng</p>
</body>
</html>

Các Media Type

TypeMô tả
allTất cả thiết bị (mặc định)
screenMàn hình máy tính, điện thoại, tablet
printMáy in, print preview
speechScreen reader, speech synthesizer

Media Features phổ biến

FeatureGiá trịVí dụ
width<length>(width: 800px)
min-width<length>(min-width: 768px)
max-width<length>(max-width: 420px)
height<length>(height: 600px)
orientationportrait | landscape(orientation: landscape)
aspect-ratio<ratio>(aspect-ratio: 16/9)
resolution<resolution>(min-resolution: 2dppx)
prefers-color-schemelight | dark | no-preference(prefers-color-scheme: dark)
prefers-reduced-motionreduce | no-preference(prefers-reduced-motion: reduce)
prefers-contrasthigh | low | no-preference(prefers-contrast: high)
hoverhover | none(hover: hover)
pointerfine | coarse | none(pointer: coarse)

Toán tử logic

/* AND - kết hợp nhiều điều kiện */
@media screen and (min-width: 768px) and (max-width: 1024px) { ... }

/* OR - dấu phẩy (comma) */
@media (max-width: 480px), (orientation: landscape) { ... }

/* NOT - phủ định */
@media not print { ... }

/* ONLY - chặn trình duyệt cũ không hiểu media query */
@media only screen and (min-width: 768px) { ... }

Đặt Media Queries trong CSS

  • Internal: Trong <style> (như ví dụ)
  • External: <link rel="stylesheet" media="screen and (max-width: 420px)" href="mobile.css">
  • @import: @import url(mobile.css) screen and (max-width: 420px); (không khuyến nghị — chặn tải song song)