🚨 Warning !
Till this date (2025-11-20), the
if()function still only have limited availability across some browsers. This includes: Chrome/Edge 137+ and Opera 121+ Versions; And it is not yet supported by Safari and Firefox !
Introduction
if() - Conditional Property Value in CSS
The
if()CSS Function allows different values to be set for a property depending on the result of a conditional test. The test can be based on a style query, a media query, or a feature query. (More test may be supported in the future)– MDN Documents : Web › CSS › Reference › Values › if()
attr() - Retrieve from HTML Data Attribute in CSS
The
attr()CSS function is used to retrieve the value of an attribute of the selected element and use it in a property value, similar to how thevar()function substitutes a custom property value.(*It can also be used with pseudo-elements, in which case the attribute’s value on the pseudo-element’s originating element is returned.)
– MDN Documents: Web › CSS › Reference › Values › attr)
Basic Usage
if() - Style/Media/Support Queries



(Source code: index-if-function-showcase.html)
attr() - Color/Unit/Transformation



(Source code: index-attr-function-showcase.html)
Combined Usage if() & attr()

https://codepen.io/SuoweiHu/pen/emZEQxj
(Basically you first save the data-attribute to a css custom property, and use the style query to check the custom property value and branch to different styling based on its value.)
Reference
- MDN Documents : Web › CSS › Reference › Values › if()
- MDN Documents: Web › CSS › Reference › Values › attr)
- Chrome for Developers: Blog > CSS attr() gets an upgrade
- Chrome for Developers: Blog > CSS conditionals with the new if() function
