if/else condition in CSS

Given an HTML file and we need to apply using if-else conditions in CSS.

No, We can not use if-else conditions in CSS as CSS doesn’t support logics. But we can use some alternatives to if-else which are discussed below:

Method 1: In this method, we will use classes in HTML file to achieve this. We will define different class names according to the conditions which we want to apply in CSS.

  • Suppose we want to change the color of text according to the line number then the if-else condition will be:
       color : red;
       color : green;
  • By using the above-discussed method, we will create classes and then apply CSS in it:
       color : red;
       color : green;

So, the above classes will execute only for HTML tags in which these classes are used.






        If-else condition in CSS
    <!-- Applying CSS -->
        /* First line CSS */
            color : red;
        /* Second line CSS */
            color: green;
<body style="text-align:center;"
    <h1 style="color:green;"
        If-else condition in CSS
    <span class="color-line1">This is first line</span>
    <span class="color-line2">This is second line</span>



Method 2: We can use CSS preprocessors like SASS which allows us to write condition statements in it. Even if you use SASS you have to pre-process your stylesheets which means that the condition are evaluated at compile time, not at run time.


$type: line;
p {
  @if $type == line1 {
    color: blue;
  } @else if $type == line2 {
    color: red;
  } @else if $type == line3 {
    color: green;
  } @else {
    color: black;

To know more about SASS click here
To read about if-else in SASS click here

My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Article Tags :

Be the First to upvote.

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.