Skip to content

Help us create more tutorials! Make a donation using the Donate button or become a member using the button below to hide this banner and track your progress.

Create a breakpoint – CSS

Demo

Click on the Edit on CodePen button in the corner and try resizing the window to see the color change at different breakpoints.

Summary

To create a breakpoint in CSS, use a media query:

@media screen and (min-width: 576px) {
  p {
    /* add properties here */
  }
}

Details

A media query allows you to apply some CSS styles only when certain conditions are met. The most common examples are applying styles when the screen or browser window is larger or smaller than a certain width.

In the example above, the rule sets inside the media query are only applied when the window or screen size is greater than 576px.

You can also use the max-width media feature to target windows or screens that have a width smaller than the listed pixel size:

@media screen and (max-width: 576px) {
  p {
    /* add properties here */
  }
}

Multiple breakpoints

If you’re using multiple media queries, it’s important that you write them in the correct order. For example, if you’re using the min-width media feature, you’ll want to start with the smallest media query and work your way up, like this:

@media screen and (min-width: 576px) {
  p {
    /* add properties here */
  }
}

@media screen and (min-width: 768px) {
  p {
    /* add properties here */
  }
}

@media screen and (min-width: 992px) {
  p {
    /* add properties here */
  }
}

This ensures that the rules get applied at the correct breakpoint. If you started with the largest value for the min-width media feature, the rules in there would override the rules inside the smaller media queries (if they’re modifying the same properties on the same elements).

If you’re using the max-width media feature, you’d write your media queries the other way around and start with the largest value for the max-width media feature, like this:

@media screen and (max-width: 992px) {
  p {
    /* add properties here */
  }
}

@media screen and (max-width: 768px) {
  p {
    /* add properties here */
  }
}

@media screen and (max-width: 576px) {
  p {
    /* add properties here */
  }
}

Again, this ensures that the rules get applied at the correct breakpoint.

Exercises

First, recreate the CSS code in the embedded CodePen demo. Try resizing your browser window to make sure that all of the rules are being applied correctly. Then try customizing the values in the media queries.

References

Beginner’s guide to media queries on MDN

Back to: CSS Course > Intermediate CSS