How to display different content based on screen width (with css only)

Ambrose
Ambrose
Jul 23, 2017 · 1 min read

As a server side dev, I don’t know jack about doing front end UI stuff. Here’s something I learned today.

The term for this is ‘responsive’. I thought it was more complicated than this and I had to look at user agent strings and figure out all the possible ones on the server side, but no.

<style>@media all and (max-width: 959px) {
.desktop {
display: block;
}
.mobile {
display: none;
}
}
@media all and (max-width: 479px) {
.desktop {
display: none;
}
.mobile {
display: block;
}
}
</style><body><div class=”desktop”>this is the content for desktop</div>
<div class=”mobile”>this is the content for mobile</div>
</body>

Here’s the jsfiddle that I modified/stole off of this stackoverflow question:

Adjust the size of the frame to see the content switching.

Ambrose
Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade