CSS chapters

Chapter 7 of 17

Conditional Statements

Try this in our CSS Compiler →

Making decisions

Real programs constantly choose between actions: log the user in or show an error, charge full price or apply a discount. The if statement is how CSS expresses that choice. The condition is evaluated and if it is true the block runs; otherwise the else block (if present) runs instead.

@media (max-width: 600px) {
  .sidebar { display: none; }
}
@media (prefers-color-scheme: dark) {
  body { background: #111; color: #eee; }
}

else if and switch

When you have more than two branches, else if chains keep the code linear and easy to read. For matching a single value against many constants, some languages offer a switch or match statement that is cleaner than a long chain.

Truthy and falsy

CSS treats certain values as automatically "true" or "false" inside a condition. Zero, empty strings and the null value are usually falsy, while everything else is truthy. Learning these rules avoids subtle bugs.

Try it yourself

CSS Compiler
Output
Code runs in a sandboxed preview inside your browser — your code is saved locally for next time.