Responsive Design β Adapting to All Screens
After completing this topic
You will understand media queries, the mobile-first strategy, and key patterns for responsive layouts.
One Code, All Screens
Websites are viewed on desktops, tablets, and smartphones. The screen sizes differ. Responsive Design is the practice of changing the layout with a single HTML/CSS to fit all screen sizes.
Viewport Meta Tag
The first step in responsiveness:
<meta name="viewport" content="width=device-width, initial-scale=1" />Without this tag, mobile browsers render the page at desktop size and then zoom out. The text becomes very small.
Media Queries
/* Default styles (mobile) */
.container {
display: flex;
flex-direction: column;
}
/* When the screen is 768px or wider (tablet) */
@media (min-width: 768px) {
.container {
flex-direction: row;
}
}
/* When the screen is 1024px or wider (desktop) */
@media (min-width: 1024px) {
.container {
max-width: 1200px;
margin: 0 auto;
}
}Media Queries apply different CSS based on screen size. min-width means "when the width is greater than or equal to".
Mobile First
Writing the default styles for mobile as in the above code, and adding styles as the screen gets larger, is called Mobile First.
The opposite, creating for desktop first and then adapting to smaller screens, is "Desktop First". Mobile First is recommended. The reasons:
- There are more mobile users.
- It is easier to expand from a layout that focuses on the essentials for small screens.
- It is more difficult to cram a complex layout for large screens into a small screen.
Use of Relative Units
Relative units are better for responsiveness than fixed units:
/* Fixed β can overflow the screen */
.box { width: 800px; }
/* Relative β adapts to the screen */
.box { width: 90%; max-width: 800px; }
/* rem β proportional to the user's font size */
.title { font-size: 2rem; }Instead of a fixed size, use:
img {
max-width: 100%;
height: auto;
}It automatically shrinks if it is larger than the container, while maintaining the aspect ratio.
Common Breakpoints
320px β Small mobile
375px β Standard mobile (iPhone)
768px β Tablet
1024px β Small desktop
1280px β DesktopYou don't need to stick to these numbers. It's best to set breakpoints where the content breaks.
Key Takeaways
Responsive design applies different CSS based on screen size using Media Queries. It is recommended to write in Mobile First and expand to larger screens. Use relative units (%, rem) and
max-widthtogether instead of fixed units (px).