Responsive web design
Responsive web design (RWD) is a web design approach to make web pages render well on all screen sizes and resolutions while ensuring good usability. It is the way to design for a multi-device web.
Setting the Viewport
To create a responsive website, add the <meta>
tag to all your web pages:
<meta name="viewport" content="width=device-width, initial-scale=1.0">
This will set the viewport of your page, which will give the browser instructions on how to control the page's dimensions and scaling.
Responsive Layout techniques
- Flexbox and Grid are responsive by default.
First ensure that all HTML elements have the box-sizing
property set to border-box
. This makes sure that the padding and border are included in the total width and height of the elements.
* {
box-sizing: border-box;
}
- Grid View
By using a flexible grid, you can change a feature or add in a breakpoint and change the design at the point where the content starts to look bad.
/* Example */
.container {
display: grid;
grid-template-columns: 1fr 1fr 1fr;
}
- Flexbox
In flexbox, flex items shrink or grow, distributing space between the items according to the space in their container. By changing the values for flex-grow
and flex-shrink
you can indicate how you want the items to behave when they encounter more or less space around them.
/* Example */
.container {
display: flex;
}
.item {
flex: 1;
}
Responsive Images/Media
To ensure media is never larger than its responsive container, the following approach can be used.
If the width property is set to a percentage and the height property is set to "auto", the media will be responsive and scale up and down:
img {
max-width: 100%;
height: auto;
}
The <picture>
element enables providing multiple sizes along with "hints" (metadata that describes the screen size and resolution the image is best suited for), and the browser will choose the most appropriate image for each device, ensuring that a user will download an image size appropriate for the device they are using.
<picture>
<source srcset="img1.jpg" media="(max-width: 400px)">
<source srcset="img2.jpg">
<img src="img2.jpg" alt=""> // <!-- for browsers that do not support the <picture> element -->
</picture>
Responsive texts - we set font sizes using %, vw, vh, etc.
This ensures that text sizes are responsive, adjusting automatically until reaching a certain limit. Once the limit is reached, the content is justified to fit within the available width.