CSS Equivalent of the “if” statement

I’d say the closest thing to “IF” in CSS are media queries, such as those you can use for responsive design. With media queries, you’re saying things like, “If the screen is between 440px and 660px wide, do this”. Read more about media queries here: http://www.w3schools.com/cssref/css3_pr_mediaquery.asp, and here’s an example of how they look:

@media screen and (max-width: 300px) {
  body {
     background-color: lightblue;
  }
}

That’s pretty much the extent of “IF” within CSS, except to move over to SASS/SCSS (as mentioned above).

I think your best bet is to change your classes / IDs within the scripting language, and then treat each of the class/ID options in your CSS. For instance, in PHP, it might be something like:

<?php
  if( A > B ){
echo '<div class="option-a">';
} 
    else{
echo '<div class="option-b">';
}
?>

Then your CSS can be like

.option-a {
background-color:red;
}
.option-b {
background-color:blue;
}

Leave a Comment