Open In App

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.

if(line1){
   color : red;
}else{
   color : green;
}
.color-line1{
   color : red;
}
.color-line2{
   color : green;
}

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






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

Output:



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.
Syntax:

$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
Supported Browsers:

CSS is the foundation of webpages, is used for webpage development by styling websites and web apps.You can learn CSS from the ground up by following this CSS Tutorial and CSS Examples.


Article Tags :