0

I have a question which I can't find answered Googling around. I would like to know if there's a way to access elements attributes from CSS3 code itself (CSS for simplicity). I'm not looking for other solutions that make use of JavaScript or CSS classes and ids because I know well how to solve the problem in that way. My question is very specific.

As an example, let's say that I have the following CSS code:

body { color: black;}
p { color: green;}

and suppose that I want to set the color CSS attribute value of a specific tag/class/id to be the same as <body> by referencing it and not just placing a simple color:black specification. In other word, I would like to have something like this:

.mySpecificP { color: body.color;}

The HTML code should be something like this:

<html>
    <head>
        <style>
            body { color: black;}
            p { color: green;}
            .mySpecificP { color: body.color;}
        </style>
    </head>

    <body>
        <p>This is a green paragraph.</p>
        <p class="mySpecificP">This is a black paragraph.</p>
    </body>
</html>

Here I'm using <p> just as an example. I'm wondering if there's a solution to the body.color pseudo-code I used in the CSS definition of mySpecificP class.

3
  • 1
    No you can't do this with vanilla CSS. You'd have to use a CSS pre-processor like Sass to do this, and then compile it into actual CSS before the browser can parse it. Commented Nov 12, 2015 at 19:15
  • It hurts.. :p there isn't a way to achieve this using inherit or something similar? Perhaps a color:root? Commented Nov 12, 2015 at 22:57
  • Children can inherit some properties from their parents. Commented Nov 13, 2015 at 6:57

1 Answer 1

1

You can achieve this with currentColor like so:

body { 
  color: black;
}

p { 
  color: green;
}

.mySpecificP { 
  color: currentColor;
}

Basically currentColor contains elements inherited color value (in this case from body) and can also be used on other properties like background-color, border-color, etc.

Working example

All relatively modern browsers are supported

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.