CSS Equivalent of the “if” Statement

An “if” or “if-else” statement is a conditional statement that works in such a way that if the “if-statement” is true, the compiler will execute the operation defined after that. But, the problem here is that “if” statements are restricted to only programming languages like Java, JavaScript, Python, C++, etc., and cannot be used by the front-end development languages like HTML and CSS.

Since CSS is a style sheet language and cannot execute logic, unlike programming languages, we cannot write an “if” statement in CSS, but there are alternatives to using the “if” condition in CSS.

In this article, we will discuss an alternative method to perform a conditional operation in HTML without using the actual “if” statement. This means applying conditions in CSS without the actual “if” statement is possible.

Using CSS Selectors | Alternative Method

In the CSS style element, create class selectors that refer to the classes created in the HTML document for which the CSS “if” alternative solution is required. And then, inside the class selector, write the property to perform any task like “color: purple,” which means that the color of the elements in the selected class should be changed to purple.

To create conditions for the execution of CSS properties, let’s create multiple classes, each containing some text information:

<span class = "line1">

<h2>This is the first line!</h2></span>

<span class = "line2">

<h2>This is the second line!</h2></span>

<span class = "line3">

<h2>This is the third line!</h2></span>

To instruct the compiler to perform “if” statement tasks (like “if” this particular class is selected, “then” this particular thing will happen), we can create multiple class selectors in the CSS style element:

.line1 {

  color : purple;


.line2 {

  color : green;


.line3 {

  color : blue;


The above code will produce the following output:

The above figure clearly shows that the program has been executed according to the conditions we applied in the CSS style element.

This sums up the CSS method equivalent to the “if” programming statement.


There is no “if” statement in the CSS stylesheet language but there is an alternative method to perform the same task in CSS. It is possible to create conditions for the execution of specific CSS properties by adding class selectors in the CSS style elements that will work in such a way that they define operations to execute referring to the specific classes.

About the author

Hadia Atiq

A Software Engineer and Technical Writer passionate about learning and spreading knowledge of the latest technology. I utilize my writing skills to help readers understand the importance and usage of modern technology.