Skip to content

Instantly share code, notes, and snippets.

@basham
Last active May 21, 2024 16:49
Show Gist options
  • Save basham/3b24062dfaecaa712a68 to your computer and use it in GitHub Desktop.
Save basham/3b24062dfaecaa712a68 to your computer and use it in GitHub Desktop.
CSS Media Queries: Best Practices

CSS Media Queries: Best Practices

/* Style for every viewport width. */
.Component {
  background-color: tomato;
  color: black;
}

/* Style for viewports greater than 320px wide. */ 
@media (min-width: 20em) {
  .Component {
    background-color: blue;
  }
}
@preagan
Copy link

preagan commented Dec 7, 2019

Thanks for posting this! I'm trying to understand this one detail...

Until there's wider rem support within media query, rem should be avoided in media query definitions as well.

Neither of the two links referenced seem to be working for me, and according to Can I Use, rem support seems to be universal.

So what am I missing? Excepting very old browsers, wouldn't rem use now be OK?

@tomygrenier
Copy link

tomygrenier commented Dec 9, 2019

Hi @basham,
I like this way of doing. I will now integrate it in my new projects.
And as @preagan says, links about REM are broken. Before reading here, I was thinking that working with rem was easier 'cause em as a lot of inheritances and it's harder to follow what size will inherit elements from their parents.

Thanks for your post. I like to learn about working better. :)

@basham
Copy link
Author

basham commented Dec 17, 2019

@preagan At the time I wrote this nearly four years ago, rem support was a little iffy. At this point, yes, rem would be perfectly fine to adopt, without reservation.

@tomygrenier I use rem almost exclusively in my projects (enterprise web apps). It fits many more use cases than other CSS units.

I'm still wrestling with identifying a new recommendation for the units within a media query. I've found some articles on this topic from a couple years ago, along with some counter arguments. If you all come to come conclusion yourself, I'd like to hear it. If I settle on a new direction, I'll update the recommendations in this Gist. Thanks for pointing out the broken links!

  1. PX, EM or REM Media Queries? (March 2016)
  2. Units for Media Queries – different conclusion (April 2017)
  3. Don't Use Em for Media Queries (November 2017)

@Tecayehuatl
Copy link

"Never use media queries to define styles for the smallest viewport size." I would edit this point, because only works for progressive enhancement, not for graceful degradation(at least not for this best practices list).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment