Zz Tux Zz Tux - 6 months ago 19
CSS Question

How to use a defined property value as another property in pure CSS?

How to use a defined property value as another property in pure CSS just like this:

.test {
color: #66ccff;
text-shadow: 0 0 8px valueOf(color);
}


'color' can be changed at anytime.

Answer

How to use a defined property value as another property in pure CSS

You can't do that in all cases but for this particular case you can use the currentColor keyword. The keyword always points to the current color applied to the element. This keyword has reasonably good browser support too (from IE9+).

If you need to use the value that is defined for one property (other than color) as the value for another then you should consider using CSS variables (browser support is pretty low at present) or use some CSS pre-processor like Sass or Less.


Using currentColor keyword:

In the below snippet you can see how the text shadow's color automatically changes when you hover.

div {
  color: #66ccff;
  text-shadow: 0 0 8px currentColor;
  font-size: 40px;
}
div:hover {
  color: yellowgreen;
}
<div>Some text</div>


Using CSS Variables:

If your target browsers are only those that support CSS variables then you could use variables like in the below snippet. Here you can see how the variables have a default value in the document root and then their value is changed when the element is hovered.

The browser support details for CSS variables feature is available @ Can I Use.

:root{
  --color: #66ccff;
  --border-width: 2px;
}
div {
  color: var(--color);
  border: var(--border-width) solid var(--color);
  text-shadow: 0 0 8px var(--color);
  font-size: 40px;
}
div:hover {
  --border-width: 4px;
  --color: yellowgreen;
}
<div>Some text</div>