CSS media queries

adjusting our stylesheets for differently-sized screens
// updated 2025-05-01 09:22

We can use @media queries in CSS to provide different stylings for differently-sized screens (as well as customize the size ranges):

/* mobile */
@media (max-width: 768px) {
  .card {
    width: 100%;
  }
}

/* tablet */
@media (min-width: 768px) and (max-width: 1024px) {
  .card {
    width: 50%;
  }
}

/* desktop */
@media (min-width: 1024px) {
  .card {
    width: 33%;
  }
}

Note that each @media query creates an additional layer of nesting of curly braces!

The example above uses typical ranges for mobile (smartphone), tablet and desktop screens. In each query, we can then have different values for the .card width depending on the screen size.

Note also that we can have multiple selectors in each query:

/* mobile */
@media (max-width: 768px) {
  .card {
    width: 100%;
  }
  .sidebar {
    width: 100%;
  }
}

/* tablet */
@media (min-width: 768px) and (max-width: 1024px) {
  .card {
    width: 50%;
  }
  .sidebar {
    width: 100%;
  }
}

/* desktop */
@media (min-width: 1024px) {
  .card {
    width: 33%;
  }
  .sidebar {
    width: 25%;
  }
}
⬅️ older (in textbook-css)
🎨 CSS reset
newer (in textbook-css) ➡️
CSS flex 🎨
⬅️ older (in code)
🎨 CSS reset
newer (in code) ➡️
CSS flex 🎨
⬅️ older (posts)
🎨 CSS reset
newer (posts) ➡️
CSS flex 🎨