Media Queries in CSS
Learn how to make your website responsive on desktops, tablets, and mobile phones, using media queries in CSS.
What are media queries ?
In CSS, media queries are used to apply styles on your website based on the properties of the user’s device. It helps you make your website responsive on all devices (desktops, tablets, and mobile phones).
Video Tutorial
If you prefer following a video tutorial, here you are:
We will be using a grid column. So let’s say you have a row container with 12 columns in it.
<div class="row">
<div class="col">1</div>
<div class="col">2</div>
<div class="col">3</div>
<div class="col">4</div>
<div class="col">5</div>
<div class="col">6</div>
<div class="col">7</div>
<div class="col">8</div>
<div class="col">9</div>
<div class="col">10</div>
<div class="col">11</div>
<div class="col">12</div>
</div>
First, we will tell that the row will be a grid having 12 columns in total. While having each column equally sized.
.row {
display: grid;
grid-template-columns: repeat(12, 1fr);
grid-gap: 5px;
}
Media Query for Desktop
For desktop devices, you can write the following media query in CSS.
/* for desktop */
@media (min-width: 992px) {
.col {
grid-column: auto/span 1;
}
}
It will check if the device width exceeds 992px, then it will divide the column into 12 parts. i.e. 12 / 1 = 12 columns
Media Query for Tablet
The following media query will be used for tablet devices.
/* for tablets */
@media (min-width: 768px) and (max-width: 991px) {
.col {
grid-column: auto/span 3; /* 12 / 3 = 4 columns for tablet */
}
}
Media Queries for Mobile and Small Devices
For mobile devices, we will show 2 columns, and for small phones (having a resolution of less than 767px) we will show 1 column.
/* for mobile */
@media (max-width: 767px) {
.col {
grid-column: auto/span 6; /* 12 / 6 = 2 columns for mobile */
}
}
/* for small devices */
@media (max-width: 320px) {
.col {
grid-column: auto/span 12; /* 12 / 12 = 1 column for small devices */
}
}
That’s it. That’s how you can use media queries in CSS and make your website responsive for all devices. If you face any problem in following this, kindly do let me know.