GibsonFX
GibsonFX

Reputation: 1060

Can you combine CSS variables to include the property and the value?

While I know you can't write variables like

root: {
--aic: align-items:center;;
}

Is there anyway to get round this, by combining the various parts seperately? The obvious obstical here is the requirement of the colon inside the variable.

i.e.

root: {
    --ai: align-items:;
    --center: center;
    --aic:
    var(--ai)
    var(--center);
    }

.myclass {var(--aic);}

Upvotes: 0

Views: 1100

Answers (2)

Simp4Code
Simp4Code

Reputation: 1479

Based on my comment on your question, you can use classes to achieve something similar. But you can't use custom properties as CSS properties, only values -- it's the same as saying for example margin: margin: var(--customMargin);;

/* Layout unrelated to answer */
div { border: 1px solid black; color: white }
.varText { background-color: red }
.varPad { background-color: blue }
.varText.varPad { background-color: green }


/* Answer */
:root { --size: 1rem }

.varText { font-size: var(--size) }
.varPad { padding: var(--size) }
<div class="varText">
  Size Text only to root variable
</div>
<div class="varText" style="--size: 2rem">
  Size Text only to inline variable
</div>
<div class="varPad">
  Size Padding only to root variable
</div>
<div class="varPad" style="--size: 2rem">
  Size Padding only to inline variable
</div>
<div class="varText varPad">
  Size Text and Padding to root variable
</div>
<div class="varText varPad" style="--size: 2rem">
  Size Text and Padding to inline variable
</div>

Upvotes: 1

Rok Benko
Rok Benko

Reputation: 22910

I would suggest you to switch to SCSS and use a @mixin. Read more about it here.

Here's a live demo.

HTML:

<div id="test">TEST</div>

SCSS:

:root {
    --text_color: red;
    --background_color: gold;
}

@mixin my_mixin {
  color: var(--text_color);
  background-color: var(--background_color);
}

#test {
  @include my_mixin;
}

Upvotes: 1

Related Questions