A Detailed Explanation of Media Queries in CSS

A Detailed Explanation of Media Queries in CSS

I. Basic Concept of Media Queries
Media Queries are a crucial feature of CSS3 that allow content to adapt to different device conditions (such as screen size, resolution, etc.). They consist of a media type and one or more conditional expressions that detect media features.

II. Syntax Structure of Media Queries

@media media-type and (media-feature) {
  /* Corresponding CSS Rules */
}
  • Media Types: screen, print, all, etc.
  • Media Features: max-width, min-width, orientation, etc.
  • Logical Operators: and (and), not (not), only (only), etc.

III. Detailed Analysis of Media Features

  1. Width-related Features:

    • min-width: Takes effect when the viewport width is greater than or equal to the specified value.
    • max-width: Takes effect when the viewport width is less than or equal to the specified value.
    /* Applied when screen width ≥ 768px */
    @media (min-width: 768px) { ... }
    
    /* Applied when screen width ≤ 1024px */
    @media (max-width: 1024px) { ... }
    
  2. Height-related Features:

    • min-height: Minimum height.
    • max-height: Maximum height.
  3. Orientation Feature:

    • orientation: landscape (landscape mode).
    • orientation: portrait (portrait mode).

IV. Practical Application of Responsive Breakpoints
Common Breakpoint Setting Strategies:

/* Mobile-First: Start designing for small screens */
.container { width: 100%; }

/* Tablet Devices */
@media (min-width: 768px) {
  .container { width: 750px; }
}

/* Desktop Devices */
@media (min-width: 992px) {
  .container { width: 970px; }
}

/* Large Screen Devices */
@media (min-width: 1200px) {
  .container { width: 1170px; }
}

V. Constructing Complex Media Queries

  1. Multiple Condition Combination:
/* Landscape mode and width between 600-900px */
@media (orientation: landscape) and (min-width: 600px) and (max-width: 900px) {
  .sidebar { display: none; }
}
  1. Comma Separation (OR logic):
/* Print devices OR screen width ≤ 600px */
@media print, (max-width: 600px) {
  .navigation { display: none; }
}

VI. Key Techniques for Mobile Optimization

  1. Viewport Settings:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
  1. High-Resolution Screen Adaptation:
/* Retina screen adaptation */
@media (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) {
  .logo { background-image: url('logo@2x.png'); }
}

VII. Best Practices in Actual Development

  1. Mobile-First Principle: Write mobile styles first, then progressively enhance with media queries.
  2. Use Relative Units: Avoid fixed pixels; use rem, em, percentages.
  3. Testing Methods: Use the browser's developer tools responsive design mode.

By mastering these knowledge points, you will be able to create truly responsive web designs that adapt to various devices.