The concept of responsiveness is very simple: a layout that responds to the screen size. It is an approach that makes the content of a web page adapt to the current window size.
Let’s understand this with the help of an example.
Suppose we have some web content that looks like the following design on a 1920×1080 desktop screen:
Upon changing the screen size a bit smaller, i.e., to 1366×768 resolution, we would see the following layout with a scrollbar:
Similarly, on a mobile screen with a 375×667 resolution, we would see something like the following:
According to the latest figures by Statcounter, 56.75% of the total web traffic comes through mobile phones. This figure is constantly increasing. It means that for a better user experience, it is extremely crucial for web designs to cater to all screen sizes, such as desktop, tablets, mobile phones, etc.
One common practice in creating a responsive web design is through media queries. For example:
/* On screens that are 600px wide or less, make the columns in component stack on top of each other */
@media screen and (max-width: 600px) {
.component {
flex-direction: column;
}
}
Like we discussed above, media queries give us the ability to style or size things based on the layout, i.e., the viewport size. In order to target a specific element, we can use a selector like an element class
, as we did for our component
in the above example.
However, with container queries, instead of the viewport size, we are able to query the size of the container our component
is in.
Here is a very basic example of component CSS using container queries:
@container (min-width: 700px){
.component {
display: grid;
}
}
This makes it easier for us to make our layout adjustments according to the space that’s available in the container.