Nathan Merrill
Nathan Merrill

Reputation: 8386

Conditional selector based on media query

I have the following selector:

#elem1:hover,#elem1.clicked{
      ...lots of css here...
}

When the screen is smaller than 800px, I want the selector only to be #elem1.clicked.

Thus, something like:

@media only screen and (min-width: 800px){#elem1:hover},#elem1.clicked{
      ...lots of css here...
}

Is it possible to do a conditional selector based on a media query?/

(I am using SASS, so SASS answers are acceptable, but changing the HTML isn't)

Upvotes: 0

Views: 92

Answers (2)

user3646269
user3646269

Reputation:

You can either define the base style for #elem1:hover, then apply overrides for #elem1.clicked like this:

#elem1:hover {

}

@media (min-width: 800px) {
    #elem1.clicked {

    }
}

Or, you could go more specific, and add styles depending on the case:

#elem1 {
    /* common style */
}

@media not (min-width: 800px) {
    #elem1:hover {

    }
}

@media (min-width: 800px) {
    #elem1.clicked {

    }
}

Upvotes: 0

feeela
feeela

Reputation: 29932

You can either reset the property inside the media query. Or not use those properties that differ in the rule inside combined selector. If you want that #elem1:hover should not match under 800px width you need to sy that in a separate rule.

Example:

#elem1:hover, #elem1.clicked {
    /* maybe basic styles that always apply */
}


#elem1.clicked {
    /* .clicked styles are always shown */
}

@media only screen and (min-width: 800px){

    #elem1:hover {
        /* styles only above 800px */
    }

}

Upvotes: 1

Related Questions