In this tutorial, we will learn about using media queries to create responsive layouts. The goal is to understand how to adapt your website's layout for different screen sizes, making it look great on any device.
You will learn:
Prerequisites: Basic understanding of HTML and CSS.
Media queries are a feature of CSS3 that allow content to respond to different conditions on a device such as the viewport width, device orientation, and resolution.
A media query consists of a media type and one or more expressions that limit the stylesheets' scope using media features, such as width, height, and color. For example, CSS can be applied only when the browser window is above or below a certain width or height.
A media query is written inside a @media
rule in your CSS file. An example of a basic media query that changes the background color when the viewport is 600px or smaller is as follows:
@media only screen and (max-width: 600px) {
body {
background-color: lightblue;
}
}
In the above example, only screen
refers to the type of media, and (max-width: 600px)
is the media feature. The CSS within the brackets is applied only when the media feature condition is true.
Let's start writing more complex media queries:
/* CSS for large devices */
@media only screen and (min-width: 601px) {
.container {
width: 80%;
margin: auto;
}
}
/* CSS for small devices */
@media only screen and (max-width: 600px) {
.container {
width: 100%;
}
}
In this example, for devices with a screen width of more than 600px, the width of the .container
class is set to 80% and centered using margin: auto
. For devices with a screen width of 600px or less, the width is set to 100%.
/* CSS for large devices */
@media only screen and (min-width: 601px) {
body {
font-size: 18px;
}
}
/* CSS for small devices */
@media only screen and (max-width: 600px) {
body {
font-size: 16px;
}
}
In this example, the font size of the body changes depending on the width of the device.
In this tutorial, we've learned about media queries and how to use them to create responsive designs. We've seen how to write media queries in CSS and test them.
Next steps for learning would be to practice using media queries in your own projects. You can also learn about other media features such as orientation and resolution.
As for additional resources, the MDN Web Docs is a great place to start.
Remember to test your media queries by resizing your browser window or using the device toolbar in your browser's developer tools.
Happy coding!