gradual color change by a variable - css

I want to have some visual notification when something is good, bad or in between
lets say I have a number between 0 and 100, where 100 is green (or some other predefined color) and 0 is red (or another color)
is there a way to get the color that is 67? 34? 98? with only css
so 67 in this case, could either be (67 * green + 33 * red) / 100 or some other function
another alternative would be to make a gradient (but then it wouldn't be a solid color..)

Currently, there is no stable way to do that in CSS, only. CSS calc() property will probably the way to go as the W3C specs include that you can use values from attr() for calculations. As of now, no browser supports the combination of both, but it would look like this
// HTML
<span class="color" data-val="67">67</span>
// CSS
.color {
background-color: rgb(
calc( (100 - attr(data-val)) / 100 * 255 ),
calc( attr(data-val) / 100 * 255),
0
);
}
calc() itself works quite well (with prefixes in Chrome (-webkit-) and Firefox (-moz-), but the numbers used for calculation must be set in CSS (e.g. width: calc(100% - 3em);).
Before attr() is fully supported inside calc(), you probably need to use javascript to achieve that, see example below where the span has a red background and the inner strong element has a green background color. Javascript is used to set the background opacity based on the text value. Press Run code snippet to see the result.
$(document).ready(function() {
$('.color').each(function() {
$(this).children('strong').css('background-color', 'rgba(0,255,0,'+(parseInt($(this).text()) / 100)+')');
});
});
.color {
display: inline-block;
margin: 5px;
text-align: center;
border: 1px solid #000;
background: #c00;
}
strong {
display: inline-block;
padding: 15px;
color: #fff;
text-shadow: 0 0 5px #000;
font-family: Arial;
font-size: 1.2em;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<span class="color"><strong>100</strong></span>
<span class="color"><strong>67</strong></span>
<span class="color"><strong>33</strong></span>
<span class="color"><strong>25</strong></span>
<span class="color"><strong>0</strong></span>

The only way you can do this with CSS is to write a class for every single possible color. The only way Sass can help is by programatically generating all of your classes:
#for $i from 0 through 100 {
.foo-#{$i} {
background: mix(red, green, $i * 1%);
}
}
This task can be more efficiently solved via JavaScript.

You can but it requires SASS or LESS or another pre-processor that allows CSS variables
SASS
$value: 0;
$green: 255*($value/100);
$red:255*((100-$value)/100);
div {
width:100px;
height:100px;
margin:10px;
background:rgb($red, $green , 0);
}
SassMeister Demo

Related

In css, can I access the value of a property from an element's parent?

Right now I have CSS (SASS) code that does this:
.container
background-color: red
.inner
...
border-bottom-color: red
(in this case, the .inner is a triangle, so its border color is serving as its background color)
I'd like to avoid specifying the second 'red', something like:
.container
background-color: red
.inner
border-bottom-color: attr(parent.background-color)
Is there a way to do this in pure CSS? (I can do it using SASS variables, or JS, or whatnot, but I'd like to stay within CSS.)
There's no way (currently) to do this in pure CSS, but since you mentioned you're using SASS, you could simply use a variable:
$myColor: red
.container
background-color: $myColor
.inner
border-bottom-color: $myColor
Edit
Depending on how the rest of your CSS is structured and since you're dealing with border-color you can set either border-color or color on .container and then set border-bottom-color: inherit; on .inner:
.container {
border-color: red;
background-color: red;
}
.container .inner { border-bottom-color: inherit; }
This is specific to the properties in your example, however. There is no way to explicitly inherit values across different properties.
CSS variables are in a very early stage of the specification process.
This is something that will definitely come, but you can't really use it nowadays. (MDN states that Fx 29 supports it already)
Example:
::root {
var-brand-color: red;
}
.container {
background-color: var( brand-color );
}
.container .inner {
border-bottom-color: var( brand-color );
}

bootstrap 3 built in image replacement?

While digging through mixins.less file of bootstrap 3 I found the following:
// CSS image replacement
//
// Heads up! v3 launched with with only `.hide-text()`, but per our pattern for
// mixins being reused as classes with the same name, this doesn't hold up. As
// of v3.0.1 we have added `.text-hide()` and deprecated `.hide-text()`. Note
// that we cannot chain the mixins together in Less, so they are repeated.
//
// Source: https://github.com/h5bp/html5-boilerplate/commit/aa0396eae757
// Deprecated as of v3.0.1 (will be removed in v4)
.hide-text() {
font: ~"0/0" a;
color: transparent;
text-shadow: none;
background-color: transparent;
border: 0;
}
// New mixin to use as of v3.0.1
.text-hide() {
font: ~"0/0" a;
color: transparent;
text-shadow: none;
background-color: transparent;
border: 0;
}
Has anyone been using this? Where do I specify the image that I want to replace the text? Am I right to assume that all this does is to hide text and not replacing it with an image?
Yes, this does not include an image, it only hides text. You will need to do your own image replacement, perhaps in a custom CSS rule:
.my-image-replacement {
background-image:url('myImage.jpg');
.text-hide();
}
I use the following for convenience:
.image-replacement( #url, #width, #height ) {
display: block;
width: #width;
height: #height;
background: url(#url) no-repeat left top;
.text-hide();
}
.logo {
.image-replacement( "images/logo.png", 100px, 50px );
}
Note this version is not retina - use bootstrap's .img-retina() from mixins.less instead of the background line above when you're serving hdpi images…

Creating CSS Global Variables : Stylesheet theme management [duplicate]

This question already has answers here:
How can I define colors as variables in CSS?
(19 answers)
Closed 6 years ago.
Is there a way to set global variables in css such as:
#Color1 = #fff;
#Color2 = #b00;
h1 {
color:#Color1;
background:#Color2;
}
Latest Update: 16/01/2020
CSS Custom Properties (Variables) have arrived!
It's 2020 and time to officially roll out this feature in your new applications.
Preprocessor "NOT" required!
There is a lot of repetition in CSS. A single color may be used in several places.
For some CSS declarations, it is possible to declare this higher in the cascade and let CSS inheritance solve this problem naturally.
For non-trivial projects, this is not always possible. By declaring a variable on the :root pseudo-element, a CSS author can halt some instances of repetition by using the variable.
How it works
Set your variable at the top of your stylesheet:
CSS
Create a root class:
:root {
}
Create variables (-- [String] : [value])
:root {
--red: #b00;
--blue: #00b;
--fullwidth: 100%;
}
Set your variables anywhere in your CSS document:
h1 {
color: var(--red);
}
#MyText {
color: var(--blue);
width: var(--fullwidth);
}
BROWSER SUPPORT / COMPATIBILITY
See caniuse.com for current compatability.
Firefox: Version 31+ (Enabled by default)
Supported since 2014 (Leading the way as usual.)
More info from Mozilla
Chrome: Version 49+ (Enabled by default).
Supported since 2016
Safari/IOS Safari: Version 9.1/9.3 (Enabled by default).
Supported since 2016
Opera: Version 39+ (Enabled by default).
Supported since 2016
Android: Version 52+ (Enabled by default).
Supported since 2016
Edge: Version 15+ (Enabled by default).
Supported since 2017
CSS Custom Properties landed in Windows Insider Preview build 14986
IE: When pigs fly.
It's time to finally let this ship sink. No one enjoyed riding her anyway. ☺
W3C SPEC
Full specification for upcoming CSS variables
Read more
TRY IT OUT
A fiddle and snippet are attached below for testing:
(It will only work with supported browsers.)
DEMO FIDDLE
:root {
--red: #b00;
--blue: #4679bd;
--grey: #ddd;
--W200: 200px;
--Lft: left;
}
.Bx1,
.Bx2,
.Bx3,
.Bx4 {
float: var(--Lft);
width: var(--W200);
height: var(--W200);
margin: 10px;
padding: 10px;
border: 1px solid var(--red);
}
.Bx1 {
color: var(--red);
background: var(--grey);
}
.Bx2 {
color: var(--grey);
background: black;
}
.Bx3 {
color: var(--grey);
background: var(--blue);
}
.Bx4 {
color: var(--grey);
background: var(--red);
}
<p>If you see four square boxes then variables are working as expected.</p>
<div class="Bx1">I should be red text on grey background.</div>
<div class="Bx2">I should be grey text on black background.</div>
<div class="Bx3">I should be grey text on blue background.</div>
<div class="Bx4">I should be grey text on red background.</div>
You can't create variables in CSS right now. If you want this sort of functionality you will need to use a CSS preprocessor like SASS or LESS. Here are your styles as they would appear in SASS:
$Color1:#fff;
$Color2:#b00;
$Color3:#050;
h1 {
color:$Color1;
background:$Color2;
}
They also allow you to do other (awesome) things like nesting selectors:
#some-id {
color:red;
&:hover {
cursor:pointer;
}
}
This would compile to:
#some-id { color:red; }
#some-id:hover { cursor:pointer; }
Check out the official SASS tutorial for setup instructions and more on syntax/features. Personally I use a Visual Studio extension called Web Workbench by Mindscape for easy developing, there are a lot of plugins for other IDEs as well.
Update
As of July/August 2014, Firefox has implemented the draft spec for CSS variables, here is the syntax:
:root {
--main-color: #06c;
--accent-color: #006;
}
/* The rest of the CSS file */
#foo h1 {
color: var(--main-color);
}
It's not possible using CSS, but using a CSS preprocessor like less or SASS.
Try SASS http://sass-lang.com/ or LESS http://lesscss.org/
I love SASS and use it for all my projects.
I do it this way:
The html:
<head>
<style type="text/css"> <? require_once('xCss.php'); ?> </style>
</head>
The xCss.php:
<? // place here your vars
$fntBtn = 'bold 14px Arial'
$colBorder = '#556677' ;
$colBG0 = '#dddddd' ;
$colBG1 = '#44dddd' ;
$colBtn = '#aadddd' ;
// here goes your css after the php-close tag:
?>
button { border: solid 1px <?= $colBorder; ?>; border-radius:4px; font: <?= $fntBtn; ?>; background-color:<?= $colBtn; ?>; }
You will either need LESS or SASS for the same..
But here is another alternative which I believe will work out in CSS3..
http://css3.bradshawenterprises.com/blog/css-variables/
Example :
:root {
-webkit-var-beautifulColor: rgba(255,40,100, 0.8);
-moz-var-beautifulColor: rgba(255,40,100, 0.8);
-ms-var-beautifulColor: rgba(255,40,100, 0.8);
-o-var-beautifulColor: rgba(255,40,100, 0.8);
var-beautifulColor: rgba(255,40,100, 0.8);
}
.example1 h1 {
color: -webkit-var(beautifulColor);
color: -moz-var(beautifulColor);
color: -ms-var(beautifulColor);
color: -o-var(beautifulColor);
color: var(beautifulColor);
}

LESS CSS - Change variable value for theme colors depending on body class

Getting to grips with LESS here but one thing is still a little unclear.
Lets say I have multiple color themes for my website, controlled by a class on the body tag. From this I can redefine the various colors for each element within each theme. Easy enough but fairly time consuming if I have a lot of elements to change... and a lot of themes. Every time I add a new theme I need to write out all the selectors again, with different color values.
I am basing my working so far on another post I found:
LESS.css variable depending on class
... However it still seems overly complicated for what I want to do in that I still have to write out all the selectors and include the mixin before dropping in the same CSS with the color variable.
I have created a CODEPEN HERE
I'd appreciate it if anyone had time to take a little look and advise me how I could approach this differently or how I could streamline this process.
Many thanks to anyone who helps out :)
Assuming you remain with wanting to theme it within one style sheet (and not multiple sheets as cimmanon noted in the comments), and assuming you are using LESS 1.3.2+, then the following code works to reduce the amount of duplication by setting up a loop through the classes that need theme changes.
Note that this does not work on Codepen (it is throwing an error uncaught throw #, perhaps because they are running an earlier version of LESS), but you can see it compiling correctly by putting the code into LESS's compiler.
LESS (based off your Codepen code with an added theme for demo)
//////////////////////////////////////////////////////
// CONSTANTS
#lightColour: #fff;
#darkColour: #000;
#lightBg: #fff;
#darkBg: #000;
#numberOfThemes: 3; //controls theme loop
//////////////////////////////////////////////////////
// MIXINS
//Theme Definitions by parametric mixin numbers (1), (2), etc.
.themeDefs(1) {
#lightColour: #f00;
#darkColour: #fff;
#lightBg: #f00;
#darkBg: #fff;
}
.themeDefs(2) {
//inverse of 1
#lightColour: #fff;
#darkColour: #f00;
#lightBg: #fff;
#darkBg: #f00;
}
.themeDefs(3) {
#lightColour: #cfc;
#darkColour: #363;
#lightBg: #cfc;
#darkBg: #363;
}
.curvy {
-moz-border-radius: 5px;
-webkit-border-radius: 5px;
border-radius: 5px;
}
//////////////////////////////////////////////////////
// GENERAL STYLING
* {padding: 0;margin: 0;}
html {text-align: center;}
h2 {padding: 20px 0;}
.box {
.curvy;
color: #lightColour;
background: #darkBg;
display:inline-block; width:10%; padding:20px 5%; margin:0 1% 20px 1%;
}
//////////////////////////////////////////////////////
// THEME BUILDING
.buildThemes(#index) when (#index < #numberOfThemes + 1) {
.theme-#{index} {
.themeDefs(#index);
color: #lightColour;
background: #darkBg;
.box {
color: #darkColour;
background: #lightBg;
}
}
.buildThemes(#index + 1);
}
//stop loop
.buildThemes(#index) {}
//start theme building loop
.buildThemes(1);
CSS Output (only showing the looped theme css for brevity)
.theme-1 {
color: #ff0000;
background: #ffffff;
}
.theme-1 .box {
color: #ffffff;
background: #ff0000;
}
.theme-2 {
color: #ffffff;
background: #ff0000;
}
.theme-2 .box {
color: #ff0000;
background: #ffffff;
}
.theme-3 {
color: #ccffcc;
background: #336633;
}
.theme-3 .box {
color: #336633;
background: #ccffcc;
}

Can you use if/else conditions in CSS?

I would like to use conditions in my CSS.
The idea is that I have a variable that I replace when the site is run to generate the right style-sheet.
I want it so that according to this variable the style-sheet changes!
It looks like:
[if {var} eq 2 ]
background-position : 150px 8px;
[else]
background-position : 4px 8px;
Can this be done? How do you do this?
Not in the traditional sense, but you can use classes for this, if you have access to the HTML. Consider this:
<p class="normal">Text</p>
<p class="active">Text</p>
and in your CSS file:
p.normal {
background-position : 150px 8px;
}
p.active {
background-position : 4px 8px;
}
That's the CSS way to do it.
Then there are CSS preprocessors like Sass. You can use conditionals there, which'd look like this:
$type: monster;
p {
#if $type == ocean {
color: blue;
} #else if $type == matador {
color: red;
} #else if $type == monster {
color: green;
} #else {
color: black;
}
}
Disadvantages are, that you're bound to pre-process your stylesheets, and that the condition is evaluated at compile time, not run time.
A newer feature of CSS proper are custom properties (a.k.a. CSS variables). They are evaluated at run time (in browsers supporting them).
With them you could do something along the line:
:root {
--main-bg-color: brown;
}
.one {
background-color: var(--main-bg-color);
}
.two {
background-color: black;
}
Finally, you can preprocess your stylesheet with your favourite server-side language. If you're using PHP, serve a style.css.php file, that looks something like this:
p {
background-position: <?php echo (#$_GET['foo'] == 'bar')? "150" : "4"; ?>px 8px;
}
In this case, you will however have a performance impact, since caching such a stylesheet will be difficult.
I am surprised that nobody has mentioned CSS pseudo-classes, which are also a sort-of conditionals in CSS. You can do some pretty advanced things with this, without a single line of JavaScript.
Some pseudo-classes:
:active - Is the element being clicked?
:checked - Is the radio/checkbox/option checked? (This allows for conditional styling through the use of a checkbox!)
:empty - Is the element empty?
:fullscreen - Is the document in full-screen mode?
:focus - Does the element have keyboard focus?
:focus-within - Does the element, or any of its children, have keyboard focus?
:has([selector]) - Does the element contain a child that matches [selector]? (Sadly, not supported by any of the major browsers.)
:hover - Does the mouse hover over this element?
:in-range/:out-of-range - Is the input value between/outside min and max limits?
:invalid/:valid - Does the form element have invalid/valid contents?
:link - Is this an unvisited link?
:not() - Invert the selector.
:target - Is this element the target of the URL fragment?
:visited - Has the user visited this link before?
Example:
div { color: white; background: red }
input:checked + div { background: green }
<input type=checkbox>Click me!
<div>Red or green?</div>
Update:
I've written a article regarding the below unique method in CSS-Tricks which goes into futher detail
I've devised the below demo using a mix of tricks which allows simulating if/else scenarios for some properties. Any property which is numerical in its essence is easy target for this method, but properties with text values are.
This code has 3 if/else scenarios, for opacity, background color & width. All 3 are governed by two Boolean variables bool and its opposite notBool.
Those two Booleans are the key to this method, and to achieve a Boolean out of a none-boolean dynamic value, requires some math which luckily CSS allows using min & max functions.
Obviously those functions (min/max) are supported in recent browsers' versions which also supports CSS custom properties (variables).
var elm = document.querySelector('div')
setInterval(()=>{
elm.style.setProperty('--width', Math.round(Math.random()*80 + 20))
}, 1000)
:root{
--color1: lightgreen;
--color2: salmon;
--width: 70; /* starting value, randomly changed by javascript every 1 second */
}
div{
--widthThreshold: 50;
--is-width-above-limit: Min(1, Max(var(--width) - var(--widthThreshold), 0));
--is-width-below-limit: calc(1 - var(--is-width-above-limit));
--opacity-wide: .4; /* if width is ABOVE 50 */
--radius-narrow: 10px; /* if width is BELOW 50 */
--radius-wide: 60px; /* if width is ABOVE 50 */
--height-narrow: 80px; /* if width is ABOVE 50 */
--height-wide: 160px; /* if width is ABOVE 50 */
--radiusToggle: Max(var(--radius-narrow), var(--radius-wide) * var(--is-width-above-limit));
--opacityToggle: calc(calc(1 + var(--opacity-wide)) - var(--is-width-above-limit));
--colorsToggle: var(--color1) calc(100% * var(--is-width-above-limit)),
var(--color2) calc(100% * var(--is-width-above-limit)),
var(--color2) calc(100% * (1 - var(--is-width-above-limit)));
--height: Max(var(--height-wide) * var(--is-width-above-limit), var(--height-narrow));
height: var(--height);
text-align: center;
line-height: var(--height);
width: calc(var(--width) * 1%);
opacity: var(--opacityToggle);
border-radius: var(--radiusToggle);
background: linear-gradient(var(--colorsToggle));
transition: .3s;
}
/* prints some variables */
div::before{
counter-reset: aa var(--width);
content: counter(aa)"%";
}
div::after{
counter-reset: bb var(--is-width-above-limit);
content: " is over 50% ? "counter(bb);
}
<div></div>
Another simple way using clamp:
label{ --width: 150 }
input:checked + div{ --width: 400 }
div{
--isWide: Clamp(0, (var(--width) - 150) * 99999, 1);
width: calc(var(--width) * 1px);
height: 150px;
border-radius: calc(var(--isWide) * 20px); /* if wide - add radius */
background: lightgreen;
}
<label>
<input type='checkbox' hidden>
<div>Click to toggle width</div>
</label>
Best so far:
I have come up with a totally unique method, which is even simpler!
This method is so cool because it is so easy to implement and also to understand. it is based on animation step() function.
Since bool can be easily calculated as either 0 or 1, this value can be used in the step! if only a single step is defined, then the if/else problem is solved.
Using the keyword forwards persist the changes.
var elm = document.querySelector('div')
setInterval(()=>{
elm.style.setProperty('--width', Math.round(Math.random()*80 + 20))
}, 1000)
:root{
--color1: salmon;
--color2: lightgreen;
}
#keyframes if-over-threshold--container{
to{
--height: 160px;
--radius: 30px;
--color: var(--color2);
opacity: .4; /* consider this as additional, never-before, style */
}
}
#keyframes if-over-threshold--after{
to{
content: "true";
color: green;
}
}
div{
--width: 70; /* must be unitless */
--height: 80px;
--radius: 10px;
--color: var(--color1);
--widthThreshold: 50;
--is-width-over-threshold: Min(1, Max(var(--width) - var(--widthThreshold), 0));
text-align: center;
white-space: nowrap;
transition: .3s;
/* if element is narrower than --widthThreshold */
width: calc(var(--width) * 1%);
height: var(--height);
line-height: var(--height);
border-radius: var(--radius);
background: var(--color);
/* else */
animation: if-over-threshold--container forwards steps(var(--is-width-over-threshold));
}
/* prints some variables */
div::before{
counter-reset: aa var(--width);
content: counter(aa)"% is over 50% width ? ";
}
div::after{
content: 'false';
font-weight: bold;
color: darkred;
/* if element is wider than --widthThreshold */
animation: if-over-threshold--after forwards steps(var(--is-width-over-threshold)) ;
}
<div></div>
I've found a Chrome bug which I have reported that can affect this method in some situations where specific type of calculations is necessary, but there's a way around it.
You can use calc() in combination with var() to sort of mimic conditionals:
:root {
--var-eq-two: 0;
}
.var-eq-two {
--var-eq-two: 1;
}
.block {
background-position: calc(
150px * var(--var-eq-two) +
4px * (1 - var(--var-eq-two))
) 8px;
}
concept
Below is my old answer which is still valid but I have a more opinionated approach today:
One of the reasons why CSS sucks so much is exactly that it doesn't have conditional syntax. CSS is per se completely unusable in the modern web stack. Use SASS for just a little while and you'll know why I say that. SASS has conditional syntax... and a LOT of other advantages over primitive CSS too.
Old answer (still valid):
It cannot be done in CSS in general!
You have the browser conditionals like:
/*[if IE]*/
body {height:100%;}
/*[endif]*/
But nobody keeps you from using Javascript to alter the DOM or assigning classes dynamically or even concatenating styles in your respective programming language.
I sometimes send css classes as strings to the view and echo them into the code like that (php):
<div id="myid" class="<?php echo $this->cssClass; ?>">content</div>
You could create two separate stylesheets and include one of them based on the comparison result
In one of the you can put
background-position : 150px 8px;
In the other one
background-position : 4px 8px;
I think that the only check you can perform in CSS is browser recognition:
Conditional-CSS
CSS is a nicely designed paradigm, and many of it's features are not much used.
If by a condition and variable you mean a mechanism to distribute a change of some value to the whole document, or under a scope of some element, then this is how to do it:
var myVar = 4;
document.body.className = (myVar == 5 ? "active" : "normal");
body.active .menuItem {
background-position : 150px 8px;
background-color: black;
}
body.normal .menuItem {
background-position : 4px 8px;
background-color: green;
}
<body>
<div class="menuItem"></div>
</body>
This way, you distribute the impact of the variable throughout the CSS styles.
This is similar to what #amichai and #SeReGa propose, but more versatile.
Another such trick is to distribute the ID of some active item throughout the document, e.g. again when highlighting a menu: (Freemarker syntax used)
var chosenCategory = 15;
document.body.className = "category" + chosenCategory;
<#list categories as cat >
body.category${cat.id} .menuItem { font-weight: bold; }
</#list>
<body>
<div class="menuItem"></div>
</body>
Sure,this is only practical with a limited set of items, like categories or states, and not unlimited sets like e-shop goods, otherwise the generated CSS would be too big. But it is especially convenient when generating static offline documents.
One more trick to do "conditions" with CSS in combination with the generating platform is this:
.myList {
/* Default list formatting */
}
.myList.count0 {
/* Hide the list when there is no item. */
display: none;
}
.myList.count1 {
/* Special treatment if there is just 1 item */
color: gray;
}
<ul class="myList count${items.size()}">
<!-- Iterate list's items here -->
<li>Something...</div>
</ul>
You can use not instead of if like
.Container *:not(a)
{
color: #fff;
}
Set the server up to parse css files as PHP and then define the variable variable with a simple PHP statement.
Of course this assumes you are using PHP...
This is a little extra info to the Boldewyn answer above.
Add some php code to do the if/else
if($x==1){
print "<p class=\"normal\">Text</p>\n";
} else {
print "<p class=\"active\">Text</p>\n";
}
CSS has a feature: Conditional Rules. This feature of CSS is applied based on a specific condition. Conditional Rules are:
#supports
#media
#document
Syntax:
#supports ("condition") {
/* your css style */
}
Example code snippet:
<!DOCTYPE html>
<html>
<head>
<title>Supports Rule</title>
<style>
#supports (display: block) {
section h1 {
background-color: pink;
color: white;
}
section h2 {
background-color: pink;
color: black;
}
}
</style>
</head>
<body>
<section>
<h1>Stackoverflow</h1>
<h2>Stackoverflow</h2>
</section>
</body>
</html>
As far as i know, there is no if/then/else in css. Alternatively, you can use javascript function to alter the background-position property of an element.
Yet another option (based on whether you want that if statement to be dynamically evaluated or not) is to use the C preprocessor, as described here.
You can use javascript for this purpose, this way:
first you set the CSS for the 'normal' class and for the 'active' class
then you give to your element the id 'MyElement'
and now you make your condition in JavaScript, something like the example below... (you can run it, change the value of myVar to 5 and you will see how it works)
var myVar = 4;
if(myVar == 5){
document.getElementById("MyElement").className = "active";
}
else{
document.getElementById("MyElement").className = "normal";
}
.active{
background-position : 150px 8px;
background-color: black;
}
.normal{
background-position : 4px 8px;
background-color: green;
}
div{
width: 100px;
height: 100px;
}
<div id="MyElement">
</div>
You can add container div for all your condition scope.
Add the condition value as a class to the container div. (you can set it by server side programming - php/asp...)
<!--container div-->
<div class="true-value">
<!-- your content -->
<p>my content</p>
<p>my content</p>
<p>my content</p>
</div>
Now you can use the container class as a global variable for all elements in the div using a nested selector, without adding the class to each element.
.true-value p{
background-color:green;
}
.false-value p{
background-color:red;
}
Besides the answers above, soon another way to directly use if/else -like conditions, and even more closely aligned with other scripting languages, would be via #when / #else conditionals. These conditionals would be implemented to exercise easily recognizable logic chain, for example:
#when supports(display: flex) {
.container {
display: flex
}
} #else media and (min-width: 768px) {
.container {
min-width: 768px
}
} #else {
.container {
width: 100%
}
}
As of February 2022 there is no browser support. Please see this W3C module for more info.
(Yes, old thread. But it turned up on top of a Google-search so others might be interested as well)
I guess the if/else-logic could be done with javascript, which in turn can dynamically load/unload stylesheets. I haven't tested this across browsers etc. but it should work. This will get you started:
http://www.javascriptkit.com/javatutors/loadjavascriptcss.shtml
If you're open to using jquery, you can set conditional statements using javascript within the html:
$('.class').css("color",((Variable > 0) ? "#009933":"#000"));
This will change the text color of .class to green if the value of Variable is greater than 0.

Resources