How to Use CSS Vars in CSS3 Selectors

Is it possible to use CSS vars in CSS3 selectors?

Cascading variables (i.e. the var() notation) aren't defined for use with anything but property declarations, so no, they cannot be used in selectors. Judging by their name, this makes sense, since only property declarations can cascade, not selectors. From the spec:

A variable can be used in place of any part of a value in any property on an element. Variables can not be used as property names, selectors, or anything else besides property values. (Doing so usually produces invalid syntax, or else a value whose meaning has no connection to the variable.)

Native CSS variables [unduplicated]

  • Is there another method to change the values of a variable, that not
    be the media queries and selectors?

    I assume you mean changing the value of a CSS variable outside of a rule set.

    Yes, you can. You can assign a CSS variable through the style property and the setProperty or setPropertyValue methods.

    document.body.style.setProperty('--bg', 'red');
    body {  background: var(--bg);}

    Are CSS Custom Properties global across linked CSS documents?

    In MDN:

    Custom properties participate in the cascade: each of them can appear
    several times, and the value of the variable will match the value
    defined in the custom property decided by the cascading algorithm.

    It works just like any other CSS properties. It should be declared in the ancestor of the target element. So usually it would be declared to the top-level element html or root:.

    It does not matter whether CSS custom properties are declared in an external CSS file or the same file.

    The following is a sample using two external CSS files. It works on Firefox, Safari and Chrome.

    https://thatseeyou.github.io/css3-examples/basics/customproperty.html

    variables.css :

    :root {
    --red: #f00;
    --green: #0f0;
    --blue: #00f;
    }

    style.css :

    .red {
    background-color: var(--red);
    }
    .green {
    background-color: var(--green);
    }
    .blue {
    background-color: var(--blue);
    }

    HTML :

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <link href="customproperty/variables.css" rel="stylesheet">
    <link href="customproperty/style.css" rel="stylesheet">
    <style>
    .module {
    --red: #800;
    --green: #080;
    --blue: #008;
    }
    </style>
    </head>
    <body>
    <div class="red">red</div>
    <div class="green">green</div>
    <div class="blue">blue</div>
    <div class="module">
    <div class="red">red in module</div>
    <div class="green">green in module</div>
    <div class="blue">blue in module</div>
    <div>
    </body>
    </html>

    How to Use Css Variable in React Component?

    Ok the solution to this problem is quite simple, It made me think for a while.

    The css variable that you provided works indeed.

    But when it comes to the content of a psudo element then you should provide the value with a pair of quotes and it will work fine.

    <Button
    {...configButton}
    style={{'--content': "'Login'" }}
    >

    change the "Login" into "'Login'" and this should work fine.
    thank you.

    How to use Javascript variables in CSS?

    No, you can not use javascript variables inside css, but you can change the style of an element dynamically via javascript's DOM elements, style property.

    document.getElementById("speed").style.transform = "rotate(" + speed + "deg)";

    In your case:

    var spinner = document.getElementById("spinner");
    var speed = 0;
    var addSpeed = 10;
    var slowSpeed = 2;

    //Activates Slowdown
    window.onload = loop();

    //Speed up
    function spin() {
    if (speed < 0) {
    speed = speed + 10;
    loop()
    } else {
    speed = speed + 10;
    }
    }

    spinner.addEventListener('click', spin);

    //Slowdown
    function loop() {
    setTimeout(
    function slow() {
    speed = speed - slowSpeed;
    document.getElementById("speed").innerHTML = speed;
    if (speed > 0) {
    loop();
    }

    document.getElementById("speed").style.transform = "rotate(" + speed + "deg)";

    }, 1000)
    }

    //Selectors
    function wheel() {
    spinner.src = "http://pngimg.com/uploads/car_wheel/car_wheel_PNG23305.png";
    }
    function spiral() {
    spinner.src = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/Black_bold_spiral.svg/2000px-Black_bold_spiral.svg.png";
    }

    EDIT:

    As per Vladu Ionut's answer , we can use variables in CSS.
    Advantages:

    1. It works in modern browsers.

    Disadavantage:

    1. It does not work in old browsers like:

      1. IE
      2. EDGE <= 15
      3. Chrome < 49, etc..
        ...
        ...

    EDIT:2, Update the code, as per the comment

                var spinnerImg   = undefined;            var speedTxt     = undefined;            var wheelImgUrl  = "http://pngimg.com/uploads/car_wheel/car_wheel_PNG23305.png";            var spiralImgUrl = "https://upload.wikimedia.org/wikipedia/commons/thumb/e/e8/Black_bold_spiral.svg/2000px-Black_bold_spiral.svg.png";             var speed           = 0;            var maxSpeedChange  = 10;            var slowSpeed       = 2;            var speedParam      = slowSpeed;
    /** * Function to change the image to wheel * * @Arguments: none * * @Returns: void */ function changeToWheel() { spinnerImg.src = wheelImgUrl; }
    /** * Function to change the image to spiral * * @Arguments: none * * @Returns: void */ function changeToSpiral() { spinnerImg.src = spiralImgUrl; }
    /** * Function to update speed display * * @Arguments: void * * @Returns: void */ function updateSpeedTxt() { speedTxt.innerHTML = speed; }
    /** * @Function to rotate the image * * @Arguments: void * * @Returns: void */ function rotateImg() { spinnerImg.style.transform = "rotate(" + speed + "deg)"; }
    window.addEventListener("load", function() { spinnerImg = document.getElementById("spinner"); speedTxt = document.getElementById("speed"); speed = speedParam; setInterval(function() { updateSpeedTxt(); rotateImg(); if (speedParam > slowSpeed) { speedParam -= 0.05; } if (speedParam < slowSpeed) { speedParam = slowSpeed; } speed += speedParam; }, 50);

    spinnerImg.addEventListener("click", function() { speedParam += maxSpeedChange; });
    });
                #spinner {                width: 500px;                transform-origin: center;            } 
    <!DOCTYPE html><html>    <head>     </head>    <body>        <div id="spinnerContainer">            <img id="spinner" src="http://pngimg.com/uploads/car_wheel/car_wheel_PNG23305.png"/>            <h4 id="speed">N/A</h4>        </div>        <div id="selectors">            <ul>                <button onclick="changeToWheel()">Wheel</button>                <button onclick="changeToSpiral()">Spiral</button>            </ul>        </div>        <footer>
    </footer> </body></html>

    Is there a way to interpolate CSS variables with url()?

    You can perform interpolation with most CSS functions, including rgba() (see an example here). In fact, interpolation is one of the main features of custom properties.

    But you cannot do this with url(), as url(var(--url)) is parsed not as a url( function token followed by var(--url) followed by a ), but a single url() token that is invalid because the var(--url) is being treated as a URL itself, and unquoted URLs in url() tokens cannot contain parentheses unless they are escaped. This means the substitution never actually occurs, because the parser never sees any var() expressions in the property value — indeed, your background declaration is completely invalid.

    If you didn't understand any of that, that's fine. Just know that you cannot use var() interpolation with url() due to legacy reasons.

    Even though the problem depicted in the question is related to the legacy url() token, you cannot do this by building URL tokens out of several var() expressions either, in case you were thinking of trying something like --uo: url(; --uc: ); or --uo: url("; --uc: ");, and background: var(--uo) var(--url) var(--uc);. This is because custom properties cannot contain unmatched string delimiters or parts of url() tokens (called bad URL tokens).

    If you want to specify a URL in a custom property, you need to write out the entire url() expression, and substitute that entire expression:

    :root {
    --url: url("https://download.unsplash.com/photo-1420708392410-3c593b80d416");
    }

    body {
    background: var(--url);
    }

    Or, use JavaScript instead of var() to perform the interpolation.



    Related Topics



Leave a reply



Submit