Wednesday, April 4, 2018

Responsive css using media queries

The @media queries/rule is used in media to apply the different type of styles for different media devices.

CSS Syntax
@media not|only media-type and (media feature and|or|not mediafeature) {
    CSS-Classes;
}

->@media is one type of rule by which CSS can apply as per media type and media feature.
->media type may be all, print, screen or speech.
->media feature may be color, grid, height, min-height,  max-height, width, min-width, max-width, etc

Ex 2: demo

style.css
body {
    background-color: white;
}

@media only screen and (max-width: 479px) {
    body {
        background-color: red;
    }
}

@media only screen and (min-width: 480px) and (max-width: 579px) {
    body {
        background-color: green;
    }
}

@media only screen and (min-width: 580px) and (max-width: 767px) {
    body {
        background-color: blue;
    }
}

@media only screen and (min-width: 768px) and (max-width: 999px) {
    body {
        background-color: yellow;
    }
}

@media only screen and (min-width: 1000px) and (max-width: 1199px) {
    body {
        background-color: black;
    }
}

@media only screen and (min-width: 1200px) and (max-width: 2000px) {
    body {
        background-color: orange;
    }
}

index.html
<html>
    <head>
        <link type="text/css" rel="stylesheet" href="style.css" />
    </head>
    <body>
        Responsive css demo
    </body>
</html>

above HTML will display with background color as par media screen.
here, default white background color will display if any media query not satisfied.
if device width is 480px, the red background color will display.
if device width is greater than 479px and less than 580 green background color will display.
same as this another media rules are applied.

here, we have only one css in @media  but we can use many CSS between @media rule/query

You can also use different style sheets for different types of media, like this

Ex 2: demo

style.css
body {
    background-color: white;
}
....
....
....

style_480.css
@media only screen and (max-width: 479px) {
    body {
        background-color: red;
    }
    ....
    ....
    ....
}

style_580.css
@media only screen and (min-width: 580px) and (max-width: 767px) {
    body {
        background-color: blue;
    }
    ....
    ....
    ....
}

index.html
<html>
    <head>
        <link rel="stylesheet" href="style.css">
        <link rel="stylesheet" media="screen and (min-width: 479px)" href="style_480.css">
        <link rel="stylesheet" media="screen and (min-width: 480px) and (max-width: 579px)" href="style_580.css">
    </head>
    <body>
        Responsive css demo
    </body>
</html>

By using @media, we can make responsive CSS design very easily and it is the most useful for responsive web applications.

No comments:

Post a Comment