Using Media Queries To Write CSS

Share

For a long time we have been able to specify styles for different media types using CSS ; print and screen being the most recognizable. With CSS3 these media types have been extended to allow additional expressions, also known as media queries, which give us greater control on when specific styles should be applied.
Media queries enable us to target specific features (screen width, orientation and resolution) within CSS itself. We can use them in two ways:
1) inline in a CSS style sheet
OR
2) as the “media” attribute in the link tag, which loads an external style sheet.

Let’s explain with a few examples.

Example – 1

/* Portrait */
@media screen and (max-width: 800px) {
    /*required css*/
}
/* Landscape */
@media screen and (min-width: 1224px) {
    /*required css*/
}

Example – 2

/* Portrait */
@media screen and (orientation:portrait) {
    /* Portrait styles */
}
/* Landscape */
@media screen and (orientation:landscape) {
    /* Landscape styles */
}

We can also write the same media query using the other method, which points to an external style sheet (not recommended):



The last example process is not recommended because it creates an additional HTTP request (bad for performance). Also, in the case of screen orientation, the separate CSS style sheet is not downloaded when the screen is rotated.

This entry was posted in CSS, HTML and tagged , . Bookmark the permalink.
 

Leave a Reply

Your email address will not be published. Required fields are marked *

*