CSS varibale in own style

Viewed 55

I'am not profficient in html and css, so i dont even know how to search for a post here in StackOverflow I excuse my selfe beforehand if this is an duplicate.

i want to do something like this:

margin-horizontal
{
   margin-left: var;
   margin-right: var;
}

<div style="margin-horizontal: 50px">

Is there a way to accomplish this behavior?

4 Answers

CSS variables are possibly what you are looking for. Your example would look as follows.

CSS:

:root {
 --space: 50px;
}

.margin-horizontal
{
   margin-left: var(--space);
   margin-right: var(--space);
}

HTML:

<div class="margin-horizontal">...</div>

To add to Chris05's answer: you can also programmatically set the CSS variables from JavaScript.

document.documentElement.style.setProperty('--space', '150px');
document.documentElement.style.setProperty('--space2', '20px');
:root {
  --space: 50px;
  --space2: 50px;
}

div {
  color: white;
  text-align: center;
  background-color: #454545;
  margin-top: 10px;
}

.margin-horizontal {
  margin-left: var(--space);
  margin-right: var(--space);
}

.margin-horizontal2 {
  margin-left: var(--space2);
  margin-right: var(--space2);
}
<div class="margin-horizontal">150px margins</div>
<div class="margin-horizontal2">20px margins</div>

Expanding on the answer by @chris05, if you want to have different values of margins for different divs, you can add a class that sets the CSS variable to a different value, for instance:

  .m-25 {
    --space: 25px;
  }

  .m-75 {
    --space: 75px;
  }

Then your default will be 50px, and if you want a different one you just add a modifier class:

<div class="margin-horizontal">Foo</div>
<div class="m-25 margin-horizontal">Bar</div>

and you'll see:

HTML rendering

What exactly are you hoping to get?

If you want to use your css class in your html you want to give the div a class with the name 'margin-horizontal'. like this: div class="margin-horizontal"

Related