Media Query and Named Anchor Example

Media queries are a key component of responsive web design. They allow you to apply different styles based on characteristics of an device, such as its width, height, or orientation.

Named anchors are a simple yet powerful feature in HTML that can greatly improve the usability of your webpages. By using the id attribute, you can create links that point to specific sections, making it easier for users to navigate your content. Please Note: You will only see the named anchor links on this page when on smaller screens thanks to media queries!

Basic Media Query

In this example, we have a box that changes its background color based on the width of the viewport:


    @media (min-width: 1025px) {
        .box {
            background-color: lightblue;
        }
    }

Resize the browser window to see the effect of the media query. When the width of the viewport is 600px or less, the background color of the box changes from lightblue to lightcoral.

Multiple Conditions

Media queries can also be combined to apply styles based on multiple conditions. For example, the following media query applies styles when the viewport width is between 601px and 1024px:


    @media (min-width: 601px) and (max-width: 1024px) {
        .box {
            background-color: lightgreen;
        }
    }
            

Resize the browser window to see the effect of this media query. When the width of the viewport is between 601px and 1024px, the background color of the box changes to lightgreen.

Orientation

Media queries can also be used to apply styles based on the orientation of the device. For example, the following media query applies styles when the device is in landscape mode:


    @media (orientation: landscape) {
        .box {
            background-color: lightyellow;
        }
    }
            

Rotate your device to see the effect of this media query. When the device is in landscape mode, the background color of the box changes to lightyellow.