Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change css style based on value

I have a boolean array that I am displaying in a razor foreach loop. Within the loop I am displaying the different values within the array. Is it possible,if so how, to change the css based on the value it is displaying?

For example

if (@status == true) THEN color = green; if (@status == false) THEN color = red.
like image 735
Matthew Czajka Avatar asked Apr 19 '17 14:04

Matthew Czajka


People also ask

How do I apply a CSS condition?

CSS Conditional Rules are nothing but a feature of CSS in which the CSS style is applied based on a specific condition. So the condition here can be either true or false and based on the statements/style will get executed. These rules eventually come under CSS at-rule as they start with an @.

Can we write condition in CSS file?

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.


2 Answers

If I understand your question correctly, you could add a data-attribute to the HTML element and alter the value (for example with Javascript) to/from "true/false" and use that in your CSS like so:

<element data-status="true">Content</element>
<element data-status="false">Content</element>

[data-status="true"] {
    color: green;
}
[data-status="false"] {
    color: red;
}
like image 132
Marco Hengstenberg Avatar answered Sep 27 '22 21:09

Marco Hengstenberg


$('.test').each(function() {
  if(parseInt($(this).css('font-size')) > 16) {
    $(this).css('color', 'green');
  }
});
.test {
  font-size: 18px;
  color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<p class="test">Javascript manipulation: Green when largen than 16px</p>
like image 28
Nick De Jaeger Avatar answered Sep 27 '22 19:09

Nick De Jaeger