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

Time:07-07

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);}

CodePudding user response:

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;
}

CodePudding user response:

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 >
  Size Text only to root variable
</div>
<div  style="--size: 2rem">
  Size Text only to inline variable
</div>
<div >
  Size Padding only to root variable
</div>
<div  style="--size: 2rem">
  Size Padding only to inline variable
</div>
<div >
  Size Text and Padding to root variable
</div>
<div  style="--size: 2rem">
  Size Text and Padding to inline variable
</div>

  •  Tags:  
  • css
  • Related