CSS Conditional Rules (original) (raw)

Last Updated : 04 Jan, 2025

CSS Conditional Rules apply CSS styles only when certain conditions are met. So the condition here can be either true or false and based on the statements/style will get executed. These rules start with the @ symbol and are part of CSS at-rules.

The main conditional rules include:

1. CSS Supports Rule

The @supports rule in CSS allows you to apply styles only if the browser supports a specific CSS property or feature.

**Syntax:

@supports ("_condition") {
/* Style to apply */
}

html `

<style>
    @supports (display: grid) {
        section h1 {
            background-color: green;
            color: white;
            padding: 15px;
        }
    }
</style>

GeeksforGeeks

A computer science portal for geeks

`

2. CSS Media Rule

The @media rule in CSS applies styles based on media queries, allowing for responsive design that adapts to different devices and screen sizes.

**Syntax:

@media screen and ("_condition") {
/* Style to apply */
}

html `

<style>
    @media screen and (max-width: 700px) {
        section {
            background-color: green;
            color: white;
            padding: 15px;
        }
    }
</style>

GeeksforGeeks

A computer science portal for geeks

`

3. CSS Document Rule

The @document rule in CSS is designed to apply styles to specific URLs or sets of URLs. However, it is currently experimental and primarily supported only in Firefox with the -moz- prefix. As a result, it is not recommended for cross-browser use.

**Syntax:

@-moz-document url("YOUR-URL") {
/* Style to apply */
}

html `

<style>
    @-moz-document url("http://localhost/GfG/document-rule.html") {
        section h1 {
            background-color: green;
            color: #fff;
            padding: 15px;
        }
    }
</style>

GeeksforGeeks

A computer science portal for geeks

`

**Note: The @document rule is not widely supported across browsers; currently, it is primarily implemented in Firefox using the @-moz-document prefix

Best Practices for Using CSS Conditional Rules