What is media queries CSS and how it works ?

Media queries are used to define different style rules for different media devices. . it is the best way to add different different CSS codes for different screen sizes .


Example

Change the background-color if the viewport is 450 pixels :



@media screen and (min-width: 450px) {
    body {
        background-color: green;
   
}
}

Definition and Usage

The @media rule is used to define different style rules for different media types/devices.
In CSS2 this was called media types, while in CSS3 it is called media queries.
Media queries look at the capability of the device, and can be used to check many things, such as:
  • width and height of the viewport
  • width and height of the device
  • orientation (is the tablet/phone in landscape or portrait mode?)
  • resolution
  • and much more
Media queries are easy to use but if you can understand logic's first . i will explain you about it in easy way .

Example ( CSS will just work in Mobile's  )

/* Mobile Layout: 320px. */
@media screen and (max-width: 767px) {
    body {
        background-color: green;
    
}

}

Example ( CSS will just work in Tablet's  )

/* Tablet Layout: 768px. */
@media only screen and (min-width: 768px) and (max-width: 991px) { 
    body {
        background-color: green;
    
}

}

Example ( CSS will just work in Medium Screens like mini laptop's , iPad pro etc .  )

/* Medium Layout: 1200px. */
@media only screen and (min-width: 992px) and (max-width: 1200px) {
    body {
        background-color: green;
    
}

}

Example ( For all desktop's or laptops  )

@media screen and (min-width: 1200px) {
    body {
        background-color: lightgreen;
   
}
}

I will make videos tutorial for it Soon . Comment below if you have any question or need any help . Thanks!

Comments