Welcome to an exciting chapter! We know that HTML, CSS, and JavaScript are the key languages that bring web pages to life. But devices like smartphones, tablets, laptops, or smartwatches which are used to view our pages come in various sizes. The solution? Responsive Web Design. It ensures that web pages detect the viewer's screen size and orientation and adjusts the layout accordingly. It's similar to words in a book reflowing to fit pages of different sizes. Now, let's delve deeper!
Before we dive into responsive design techniques, there's one critical piece you need in every responsive webpage: the viewport meta tag. Without it, mobile browsers will display your page as if it were on a desktop screen, making everything tiny and forcing users to zoom.
Add this to the <head> section of your HTML:
What does this do?
width=device-widthtells the browser to use the device's actual screen widthinitial-scale=1.0sets the initial zoom level to 100%
Without this tag, your media queries won't work properly on mobile devices! This is the foundation of all responsive design.
To make your site responsive, you should embrace CSS Media Queries. These are instrumental in Responsive Web Design. Media queries implement certain CSS rules when specific conditions are fulfilled. For example, the following is a simple media query that applies a rule when the browser window is less than 600 pixels wide:
In the above segment, screen is the media type and (max-width: 600px) is the media feature. It changes the body's background color to light blue when the viewport is 600 pixels wide or less.
Media queries modify layouts based on screen size. For example, a webpage layout on a large screen (like a desktop) would differ from that on a smaller screen (like a smartphone). Here's an example:
And the corresponding CSS in styles.css:
Note that when we give a value as a percentage, such as margin-left: 1%;, it means that the left margin is set to 1% of the total width of the parent element. For example, if the parent element has a width of 800px, a margin-left: 1%; on the child element would be equivalent to 8px.
