Responsive Web Design: Learning Simple CSS Media Queries
If you think responsive’s simple, I feel bad for you son. We got 99 viewports, but the iPhone’s just one. ~ Josh Brewer
I was coding my websites about page and just could not get my text on the html page to show in a readable manner on any device besides a laptop. All my life I just used bootstrap and other frameworks to make building sites easier and noticed they use media queries. Given this problem when building my sites about page, I thought, its time to learn how this works!
What exactly is a Media Query?
Simply put it uses the
@media rule to prioritise a block of CSS properties only if a certain condition is true.
What is a Media Rule?
@media rule is used in media queries to apply different styles for different media types/devices.
What are the Media Types?
- All - Used for all media type devices
- Print - Used for printers
- Screen - Used for screens
- Speech - Used for screenreaders
You control your media queries using media features.
Here are some of the most common ones used:
- Width and height of the viewport
- Width and height of the device
- Orientation (is the tablet/phone in landscape or portrait mode?)
I wrote my first CodePen 🥳!
I usually search for code on CodePen and always find such over complicated samples. I have created my own sample which I hope helps you easily grasp the concept...
Click here to check it out.
Heres a bonus cool CodePen that makes use of simple media queries.
Star Wars: The Force Awakens in CSS by Donovan Hutchinson
Some beginner tips
- Choose breakpoints(media rules) based on your design and not specific devices.
- Make use of media queries to improve your user experience based on device type even if it changes the layout slightly.
- You can use logical operators (and, not, only, ','[comma]) to chain multiple media queries together or to enforce specific behaviour.
- You can target a screens orientation (landscape, portrait) using media queries. This is very helpful on mobile and tablet devices.
- You can create separate stylesheets and trigger them using media queries. This makes it easier to manage your sites css based on the device that a bug was found on.
<link rel="stylesheet" href="tablet.css" media="screen and (max-width: 800px)">
<!-- applies an external stylesheet to screens up to 800 pixels wide -->
Here are some resources that helped me understand media queries:
- How To Use CSS3 Media Queries To Create a Mobile Version of Your Website by Rachel Andrew
- Using media queries by MDN Web Docs
- Media Queries Level 5 by W3C
Comment below with other useful links you have found to learn how to use media queries or better yet share a cool CodePen with everyone 😉.