How to Use Media Queries in HTML and CSS to Create Responsive Websites
As the use of smart devices continues to rise, responsive design is becoming an essential aspect of web development. Websites must be optimized for all screen sizes, including desktop, tablet, and mobile devices. One approach to achieving this is through media queries in HTML and CSS.
Media queries are conditional statements used in CSS to alter the style of a page based on the size of the device displaying it. Implementing media queries enables developers to create responsive websites that adapt to a user’s screen size without requiring them to zoom in or out.
To begin using media queries, you must first add them to the CSS file of your project. This is done by using the ‘@media’ rule followed by a set of curly braces. The curly braces contain the styling rules that apply to the specified device size.
For instance, suppose you want to modify the text size for a screen with a maximum width of 768 pixels. In that case, you would use the following code:
“`
@media only screen and (max-width: 768px) {
body {
font-size: 16px;
}
}
“`
This code specifies that the styling rules within the curly braces will apply only to screens with a maximum width of 768 pixels. In this case, the font-size will be changed to 16px for smaller screens.
Another common example of media queries in responsive website design is changing the layout of the page based on the screen size. This can be achieved with the use of flexbox or grid. Here is an example:
“`
@media only screen and (max-width: 768px) {
.container {
display: flex;
flex-direction: column;
}
.item {
width: 100%;
}
}
“`
This code specifies that the layout of the container and item elements will change for screens with a maximum width of 768 pixels. The container changes its display property to flex, and the flex-direction changes to column, making it stack vertically. The item changes its width to 100% to fill the entire container’s width.