DevNotes
@devnotes ·
CSS Part 7: Responsive design with media queries
Most people will open your site on a phone. A responsive page rearranges itself to fit whatever screen it's on.
Step one: the viewport tag
Check that your HTML has this line in the <head>. It was in the skeleton from HTML Part 1:
Without it, phones pretend to be a 980px-wide desktop and shrink your page down to fit. Nothing else in this part works without it.
Media queries
A media query applies CSS only when a condition is true, usually about the screen's width:
On screens narrower than 768px, the cards stack in one column. From 768px up, the rule inside the media query kicks in and they sit three across.
Phone first
Look at the order above: the phone layout comes first, outside any media query, and the wider layout gets added with min-width. This is called mobile-first, and it's the usual way to work. Phone layouts tend to be simpler, so you start simple and add columns as the screen grows, instead of building a desktop page and then undoing half of it.
You don't need a breakpoint for every phone model. Start with one or two, around 768px for tablets and 1024px for laptops, and add another only when your design actually breaks at some width.
Images that never overflow
Images can now shrink to fit a narrow screen, but never stretch past their real size. Put this in every project.
Text that scales
clamp() picks a size between a minimum and a maximum, growing with the screen in between:
The heading is never smaller than 1.75rem and never bigger than 3rem. In between, it's 5% of the screen's width. No media query needed.
Small screens, real fingers
- Make buttons and links at least 44px tall, so a thumb can hit them.
- Keep body text at 16px or more. Smaller text makes people pinch and zoom, and on iPhones, an input with text under 16px makes the page zoom in when it's tapped.
- Don't hide anything important behind hover. A phone has no mouse, so it may never show.
Test it
In Chrome DevTools, click the phone-and-tablet icon at the top left to open the device toolbar. Pick a phone from the list, or drag the edge to change the width and watch your layout respond. Then check it on a real phone too: paste your code into CodePen (HTML Part 1) and open the pen on your phone.
Try it
Make your portfolio responsive: one column of cards on a phone and three on a laptop, and a header that stacks your name above the menu on a phone, then puts them side by side from 768px up. Size the main heading with clamp().
Next: JavaScript Part 1: Your first lines of code
Join WIK to like and reply to DevNotes and see more like this.