{"id":334015,"date":"2021-02-17T08:05:26","date_gmt":"2021-02-17T16:05:26","guid":{"rendered":"https:\/\/css-tricks.com\/?p=334015"},"modified":"2021-02-17T08:05:29","modified_gmt":"2021-02-17T16:05:29","slug":"css-switch-case-conditions","status":"publish","type":"post","link":"https:\/\/css-tricks.com\/css-switch-case-conditions\/","title":{"rendered":"CSS Switch-Case Conditions"},"content":{"rendered":"\n
CSS is yet to have a While none of these things are usable today, there has been a good amount of chat about the concept of generic conditional CSS just in the last year:<\/p>\n\n\n\n So, yes. The demand for conditional CSS is there.<\/p>\n\n\n Perhaps a visual change after a certain amount of scrolling. A visual change after a numeric input is within a certain range. A component with a handful of states.<\/p>\n\n\n\n There is a whole genre of extremely popular JavaScript libraries for UI (e.g. React, Vue, etc.) that are essentially for building UI based on state. Clearly this is a developer need. If we could move that state-based styling to CSS, that\u2019s all the less JavaScript we might need \u2014 and maybe a better separation of concerns.<\/p>\n\n\n We already have custom properties in CSS, and we could base state-change logic on them, changing a block of styles as a side effect of the custom property changing to certain values.<\/p>\n\n\n\n It\u2019s true that we have mechanisms for changing blocks of styles already. We can change CSS Let\u2019s see see this in action by playing with the switch<\/code> rule or conditional
if<\/code>, aside from the specific nature of
@media<\/code> queries and some deep trickery<\/a> with CSS custom properties. Let\u2019s have a look at why it would be useful if we did, and look at a trick that is usable today for pulling it off.<\/p>\n\n\n\n\n\n\n
Recent chatter about the possibility<\/h3>\n\n\n
switch()<\/code> statement<\/a> and Tab Atkins riff on it<\/a>.<\/li>
Imagine why conditional CSS would be useful<\/h3>\n\n\n
A common theme<\/h3>\n\n\n
class<\/code> through JavaScript, and that
class<\/code> can apply whatever we like in CSS. But that doesn\u2019t mean state-based styling in CSS wouldn\u2019t be useful. We don\u2019t always have the ability or may not want to write any JavaScript for this, and instead change custom properties in other ways (e.g. media queries, HTML changes, etc). Doing it in CSS means helping separate business logic and visual style logic.<\/p>\n\n\n
A trick! Using
@keyframes<\/code> for state<\/h3>\n\n\n
@keyframes<\/code> can be used to
switch<\/code> specific changes. Through the power of the
animation<\/code> property, a possibility opens up to select exactly which frame to show, and have it pause exactly<\/em> on that frame, effectively mimicking a switch-case statement or state-based styles.<\/p>\n\n\n\n
animation-delay<\/code> property:<\/p>\n\n\n\n