CSS - Media Queries

-

Syntax and Structure

Media queries are a part of CSS that let you use different styles based on the device or viewport. To use media queries, you need to know their basic syntax and structure.

The basic syntax of a media query has the @media rule followed by the media type and one or more media features. The media type tells the type of device the styles should be used for, while media features describe specific things about the device or viewport.

The most common media types are:

Media Type Applies To
all All devices
print Printers and print preview modes
screen Computer screens, tablets, and smartphones
speech Screen readers and other devices that read out content

Media features are used to target specific device or viewport characteristics.

Media Feature Specifies
width The width of the viewport
height The height of the viewport
orientation The orientation of the device (portrait or landscape)
aspect-ratio The aspect ratio of the viewport

You can combine media types and features using logical operators to make more specific media queries. The available logical operators are:

Logical Operator Function
and Combines multiple media features or types
not Negates a media query
only Applies styles only if the entire query matches

Example: A media query that targets screens with a minimum width of 768px

@media screen and (min-width: 768px) {
  /* Styles for screens wider than 768px */
}

Example: Combining multiple media queries using commas

@media screen and (min-width: 768px), print {
  /* Styles for screens wider than 768px and printers */
}

Responsive Design with Media Queries

Media queries let you make responsive designs that look good on any screen size. To do this, you need to:

  1. Create breakpoints for different screen sizes
  2. Adjust layout and design based on screen size
  3. Hide or show elements based on screen size
  4. Change font sizes and spacing for better readability

Breakpoints are screen widths where your layout changes. Common breakpoints are:

Breakpoint Name Screen Width
Small < 576px
Medium ≥ 576px
Large ≥ 992px
Extra Large ≥ 1200px

You can set different styles at each breakpoint using min-width and max-width media features:

Example: CSS for different breakpoints

/* Base styles for small screens */
body {
  font-size: 16px;
}

/* Styles for medium screens */
@media screen and (min-width: 576px) {
  body {
    font-size: 18px;
  }
}

/* Styles for large screens */
@media screen and (min-width: 992px) {
  body {
    font-size: 20px;
  }
}

To adjust layout, you can change the width, margin, and padding of elements at different breakpoints. For example:

Example: Adjust layout for different breakpoints

/* Base layout for small screens */
.container {
  width: 100%;
  padding: 10px;
}

/* Layout for medium screens */
@media screen and (min-width: 576px) {
  .container {
    width: 540px;
    margin: 0 auto;
  }
}

/* Layout for large screens */
@media screen and (min-width: 992px) {
  .container {
    width: 960px;
  }
}

You can hide or show elements using the display property. Setting display: none hides an element, while display: block shows it:

Example: Hide or show elements based on screen size

/* Hide an element on small screens */
.element {
  display: none;
}

/* Show the element on medium screens */
@media screen and (min-width: 576px) {
  .element {
    display: block;
  }
}

Adjust font-size, line-height, and other spacing properties for better readability at each breakpoint:

Example: Font size and spacing adjustments

/* Base font styles for small screens */
p {
  font-size: 14px;
  line-height: 1.4;
  margin-bottom: 10px;
}

/* Font styles for medium screens */
@media screen and (min-width: 576px) {
  p {
    font-size: 16px;
    margin-bottom: 15px;
  }
}

/* Font styles for large screens */
@media screen and (min-width: 992px) {
  p {
    font-size: 18px;
    line-height: 1.6;
    margin-bottom: 20px;
  }
}

Media Queries for Different Devices

Media queries can target specific devices, such as iPhones, iPads, and Android phones. By using device-specific media queries, you can change your website's layout and design for different device screen sizes and handle device-specific features like retina displays and touchscreens.

To target specific devices, you can use the min-device-width and max-device-width media features. These features refer to the actual width of the device's screen, rather than the width of the browser viewport.

Example: Device-specific media queries

/* Styles for iPhones */
@media screen and (max-device-width: 480px) {
  /* iPhone-specific styles */
}

/* Styles for iPads */
@media screen and (min-device-width: 481px) and (max-device-width: 1024px) {
  /* iPad-specific styles */
}

/* Styles for Android phones */
@media screen and (max-device-width: 480px) and (-webkit-min-device-pixel-ratio: 2) {
  /* Android phone-specific styles */
}

When changing layout and design for different device screen sizes, consider the following:

Consideration Description
Use relative units Use relative units (e.g., percentages, em, rem) instead of fixed units (e.g., pixels) for sizes and spacing. This allows your layout to adapt to different screen sizes.
Adjust size and position of elements Change the size and position of elements to fit the available screen space. For example, you might need to stack elements vertically on smaller screens instead of displaying them side by side.
Optimize images Optimize images for different device screen sizes to avoid slow loading times and to look good on high-resolution screens.

To handle device-specific features like retina displays, you can use the device-pixel-ratio media feature. This feature describes the ratio between physical pixels and logical pixels on the device's screen.

Example: Retina display media queries

/* Styles for retina displays */
@media screen and (-webkit-min-device-pixel-ratio: 2), (min-resolution: 192dpi) {
  /* Retina-specific styles, e.g., high-resolution images */
  background-image: url('image@2x.png');
}

For touchscreens, you might need to change the size and spacing of clickable elements (e.g., buttons, links) to make them easier to tap with a finger. You can use the pointer media feature to target devices with touchscreens.

Example: Touchscreen media queries

/* Styles for touchscreens */
@media screen and (pointer: coarse) {
  /* Touchscreen-specific styles */
  button {
    padding: 15px;
    font-size: 18px;
  }
}

Examples and Demos

To help you understand how media queries work in practice, let's look at some examples and demos.

Basic Responsive Layout Example

Example: Basic Responsive Layout

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Basic Responsive Layout</title>
  <style>
    /* Base styles */
    .container {
      display: flex;
      flex-wrap: wrap;
    }
    .column {
      flex: 1;
      padding: 10px;
      background-color: #f0f0f0;
      border: 1px solid #ccc;
    }

    /* Media queries */
    @media screen and (max-width: 767px) {
      .container {
        flex-direction: column;
      }
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="column">Column 1</div>
    <div class="column">Column 2</div>
    <div class="column">Column 3</div>
  </div>
</body>
</html>

In this example, the layout has three columns that are shown side by side on larger screens. When the screen width is 767px or less, the media query changes the flex-direction to column, stacking the columns vertically.

Advanced Responsive Design Techniques

Fluid Grids

Fluid grids use relative units (e.g., percentages) for column widths, allowing the layout to adapt to different screen sizes.

Example: Fluid Grids

.container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  grid-gap: 20px;
}

This CSS creates a grid container with columns that automatically adjust their width based on the available space, with a minimum width of 200px and a maximum of 1 fraction unit (1fr).

Flexible Images

To make images responsive, you can use the max-width property:

Example: Flexible Images

img {
  max-width: 100%;
  height: auto;
}

This CSS makes sure that images never exceed the width of their container and keep their aspect ratio.