🚨 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 !

2025-11-20T154740


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 the var() 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

2025-11-20T162624

2025-11-20T162731

2025-11-20T162849

(Source code: index-if-function-showcase.html)

attr() - Color/Unit/Transformation

2025-11-20T165649

2025-11-20T165835

2025-11-20T165954

(Source code: index-attr-function-showcase.html)


Combined Usage if() & attr()

2025-11-20T170215

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