Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS Equivalent of the "if" statement

Tags:

css

Is there any way to use conditional statements in CSS?

like image 885
BreakHead Avatar asked Mar 15 '10 11:03

BreakHead


People also ask

Is there an if statement in CSS?

No, We can not use if-else conditions in CSS as CSS doesn't support logics.

Can CSS have conditionals?

CSS Conditional Rules is a CSS module that allows to define a set of rules that will only apply based on the capabilities of the processor or the document the style sheet is being applied to.

Can you have logic in CSS?

CSS Logical Properties and Values is a module of CSS introducing logical properties and values that provide the ability to control layout through logical, rather than physical, direction and dimension mappings. The module also defines logical properties and values for properties previously defined in CSS 2.1.


2 Answers

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; } 
like image 170
Aaron Mannino Avatar answered Oct 20 '22 19:10

Aaron Mannino


No. But can you give an example what you have in mind? What condition do you want to check?

Maybe Sass or Compass are interesting for you.

Quote from Sass:

Sass makes CSS fun again. Sass is CSS, plus nested rules, variables, mixins, and more, all in a concise, readable syntax.

like image 35
Felix Kling Avatar answered Oct 20 '22 21:10

Felix Kling