Conditional Styling with if()

Click the checkbox to toggle the state. The background color, text color, padding, and border radius of this card are controlled by the CSS if() function based on the checkbox's state, with no JavaScript.

--is-active: if(input:checked, 1, 0)

background-color: if(--is-active = 1, active_color, default_color)

How It Works

Browser Compatibility

This demo uses the experimental CSS if() function. It will only work in browsers that support this feature. You must enable the "Experimental Web Platform features" flag:

  • Chrome/Edge 131+: Go to chrome://flags or edge://flags

Key CSS Code

The logic is handled entirely in CSS by combining three modern features: custom properties, the :has() selector, and the if() function.

.feature-card {
    --is-active: 0; /* Default state */

    background-color: if(var(--is-active) = 1, #1e40af, #f3f4f6);
    color:            if(var(--is-active) = 1, white, #1f2937);
    border-color:     if(var(--is-active) = 1, #3b82f6, #d1d5db);
    padding:          if(var(--is-active) = 1, 2rem, 1.5rem);
    border-radius:    if(var(--is-active) = 1, 1rem, 0.5rem);
    
    transition: all 0.3s ease-in-out;
}

/* Update the state when the checkbox is checked */
.feature-card:has(input:checked) {
    --is-active: 1;
}