Responsive web design makes your web page adapt to all devices irrespective of the screen size. The elements on the page get resized or relocated when the screen (or window) size is changed.
Responsive web designing can be done with CSS and HTML and doesn’t require JavaScript or other programs. This guide will help you learn responsive web designing using CSS.
For designing responsive web pages, we need some relative units which would change based on the window size. The most frequently used relative units are %, em, rem, vw, and vh.
We need to first define a viewport that will instruct the browser to set the size of the page contents based on the width of the viewing window.
To define the viewport, we include the following meta tag to all the pages:
<meta name=”viewport” content=”width=device-width, initial-scale=1.0”>
We can make Fluid images that can change their size based on the screen size simply by using the % unit. If we set the width property of the image in % (e.g., 100%), the image will scale up or down.
Syntax: <img src=”img.jpg” style=”width:100%;”>
If you use the max-width property to set the relative image size, the image won’t be upscaled more than its original width, thus preventing the image from getting pixelated.
Syntax: <img src=”img.jpg” style=”max-width:100%; height: auto;”>
Media Queries are frequently used to design responsive web pages, and it enables the developers to make entirely unique styles for different window sizes.
Example:
@media (max-width: 500px) { .image { width: 100% } }
This code block will be executed only when the screen width is less than 500px.
Multiple media queries can be added for different page sizes.
We can also make our texts respond to the screen size by using media queries.
Example:
@media (max-width: 500px) { .myText { font-size: 14px; } }
You can guess what it does.
But there is another way of doing it: using the relative units, rem or vw.
The ‘viewport width’ or ‘vw’ forces the text to change based on the window size.
Example: <p style=”font-size: 15vw”>Responsive CSS</p>
Alternatively, this can also be done with the ‘rem’ unit. What ‘rem’ does is basically take the default font size of the HTML and scale the other text elements with respect to the default.
Example:
Html { font-size: 20px; } (This makes 1 rem = 20px) .myText { font-size: 2rem; }
This makes the font-size 40px inside the scope of ‘myText’.
Flexbox makes the entire responsive page-building process straightforward. It can be implemented inside the CSS code, and it comes with a lot of functions to make efficient layouts and evenly space items in a web page.
Syntax:
.items { display: flex; }
Congratulations! You have learned the process of designing Responsive web pages using CSS. It is a vast concept, especially flexbox, and everything could not be included in this guide. We encourage you to read more about Responsive designing and build your own web page from what you have learned.