Learn how to effectively use media queries in CSS to create responsive web pages.

Introduction to Media Types

Media types allow us to determine which media a CSS file or a piece of CSS is loaded on. The following media types are commonly used:

  • all: loads the CSS on all media types
  • print: used when printing
  • screen: used when the page is presented on a screen
  • speech: used for screen readers

By default, screen is used if no media type is specified. Media types can be used in @import statements and in the media attribute of the link tag in HTML. For example:

@import url(myfile.css) screen;
<link rel="stylesheet" type="text/css" href="myfile.css" media="screen" />

Media Feature Descriptors

Media feature descriptors are additional keywords that can be added to the media attribute of link tags or in @import declarations to add conditionals for the loading of CSS. Here are some commonly used media feature descriptors:

  • width
  • height
  • device-width
  • device-height
  • aspect-ratio
  • device-aspect-ratio
  • color
  • color-index
  • monochrome
  • resolution
  • orientation
  • scan
  • grid

Each descriptor can have corresponding min- and max- versions. Some descriptors accept length values, such as px or rem. For example:

@import url(myfile.css) screen and (max-width: 800px);

Some descriptors accept fixed values like portrait or landscape for the orientation descriptor. Example:

<link rel="stylesheet" type="text/css" href="myfile.css" media="screen and (orientation: portrait)" />

There are also descriptors that accept integers, such as color, which inspects the number of bits per color component used by the device.

Media feature descriptors can be combined using logic operators:

  • and: combines multiple conditions
  • ,: performs an “or” type of logic operation
  • not: negates a media query

For example:

@media screen and (max-width: 800px) {
  /* CSS rules for screens with a maximum width of 800px */
}

@import url(myfile.css) screen, print;

Using Media Queries for Responsive Design

Media queries can also be applied directly in the CSS using the @media rule. This is the foundation for creating responsive designs. Here’s an example of using media queries within CSS:

@media screen and (max-width: 800px) {
  /* CSS rules for screens with a maximum width of 800px */
}

Media queries can become quite complex by combining multiple conditions. For example:

@media screen and (max-width: 800px) and (min-width: 600px) and (orientation: landscape) {
  /* CSS rules for screens with a width between 600px and 800px, and landscape orientation */
}

By using media queries, you can create responsive web pages that adapt to different screen sizes and orientations.

Tags: CSS, media queries, responsive design, web development