1. Media Query
Media queries play a crucial part while developing Responsive Layouts.
Using Media queries, you can apply CSS based on the device type (e.g., printers, TVs) and media features (e.g., viewport width).
Syntax :
@media media-type and (media-feature-expression) {
/* CSS rules go here */
}
1.1 Media Types
Media types describe the general category of devices.
Possible types of media are:
- screen- For all Screened devices (mobiles, laptops, tablets, etc.)
- print- For Printers.
- tv- For Televisions.
- all- Matches all types of devices and more...
.heading { color: blue; }
@media print { .heading { color: green; } }
If the media type is not declared, it will default to all.
1.2 Media Features
Using Media Features, we can write Media Query for a specific feature(s).
- width, min-width, max-width
- height, min-height, max-height
- orientation and more...
1.2.1 width, min-width, max-width
body { margin: 0px; } .bg-container { height: 100vh; width: 100%; } @media (width: 800px) { .bg-container { background-color: deepskyblue; } } @media (max-width: 799px) { .bg-container { background-color: orange; } } @media (min-width: 801px) { .bg-container { background-color: yellowgreen; } }
In the example above, try out height, min-height, max-height.
1.2.2 Orientation
The two most common types of
orientation
are:- landscape- The width of the device is greater than the height.
- portrait- The height of the device is greater than the width.
body { margin: 0px; } .bg-container { height: 100vh; width: 100%; } @media (orientation: landscape) { .bg-container { background-color: orange; } } @media (orientation: portrait) { .bg-container { background-color: yellowgreen; } }
2. Combining Multiple Media Features in a single Media Query.
2.1 Logical Operators
2.1.1 And
- Using andoperator can combine multiple Media Features.
Syntax :
@media (media-feature-expression) and (media-feature-expression) {
/* CSS rules go here */
}
- We can also join media feature with a media type.
Syntax :
@media media-type and (media-feature-expression) {
/* CSS rules go here */
}
body { margin: 0px; } .bg-container { height: 100vh; width: 100%; } @media (orientation: landscape) and (min-width: 600px) { .bg-container { background: deepskyblue; } }
In the example above, try out the combination of media features with media types using the
and
operator.Note
If you use the
and
operator, only one media type for a media query can be included.2.1.1 Not
The
not
operator is a Media Query Modifier. It negates the entire Media Query result.Note
If you use the
not
operator, you must also specify a media type.Wrong Syntax
CSS
Correct Syntax
CSS0000
2.1.1 , (comma)
Using
,
(comma) operator we can combine multiple Media Queries.
In the example above, try out different combinations of media queries using the
,
(comma) operator.