← Back to CSS
61

Logic in CSS: the `if()` function and style queries

Introduce native conditional logic into your style sheets. Learn how to switch properties based on variable values without writing a line of JavaScript.

📘 Theory

The conditional `if()` function

Syntax: condition ? true value : false value.

The `if()` function lets you assign a property value based on a logical test. Its shape is similar to the ternary operator in JavaScript: `if( ? : )`.

That is especially useful for component states. You can define a variable such as `--size` and let `if()` decide the `padding`, `font-size` or `border-radius` without creating extra classes like `.btn--small` or `.btn--large`.

The important idea is that `if()` works best alongside custom properties, making CSS feel more programmable and less repetitive.

Style queries

`@container style(--variable: value)`

1

Traditional container queries inspect the size of the parent. Style queries inspect the style of the parent. If a container exposes `--theme: dark`, its children can react automatically.

2

That solves many context problems. Instead of selectors such as `.dark-mode .card .title`, the component can ask whether it lives inside a dark context and adjust itself accordingly.

3

The base syntax is `@container style(--featured: true) { ... }`. This makes components aware of their environment in a more granular and reusable way.

🧪 Learn by doing

Example Demo: the intelligent component Change the variable value in the CSS and see how the button reacts through internal logic without modifying the HTML.
Example Challenge: context adaptation We have a weather widget. If the container exposes `--weather: rainy`, turn the icon blue. If it is `--weather: sunny`, turn it orange.

What is this?

I'm Cristian Eslava and I sometimes build websites so both you and I can learn and experiment. culTest

I made this in February 2026 to make learning easier for my students. The idea is to learn web development by practicing and to keep expanding the project with new topics, tests and challenges.

It draws inspiration from MDN, W3Schools, CodePen, Manz and many other web development references. I wanted to combine useful theory, runnable examples, challenges and the testing system I had already built for culTest. culTest

If you liked it, if you didn't, or if you want to get in touch, write to me at cristianeslava@gmail.com