CSS3 Media Queries: Change Background Color

One way to use media queries is to have an alternate CSS section right inside your style sheet. The following example changes the background-color to lightgreen if the viewport is 480 pixels wide or wider (if the viewport is less than 480 pixels, the background-color will be pink):

HTML file: Displayed by browser:
<style>
body {
    background-color: pink;
}
@media screen and (min-width: 480px) {
    body {
        background-color: lightgreen;
    }
}
</style>
<body>
<h1>Resize the browser window to see the effect!</h1>
<p>The media query will only apply if the media type is screen and the viewport is 480px wide or wider.</p>
</body>

Resize the browser window to see the effect!

The media query will only apply if the media type is screen and the viewport is 480px wide or wider.


Back button Table of Contents Next button