Search code examples
csscss-selectorscss-variables

How can I solve this css behaviour?


I would like to make a stack css class, where every element which is followed by an element has a margin-top, like:

.stack > * + *{
    margin-top:var(--stack-gap);
}

now, with the --stack-gap var I can set a stack spacing. Like:

.stack > * + * {
  margin-top: var(--stack-gap);
}
<div class="stack" style="--stack-gap:20px">
  <div>...</div>
  <div>...</div>
</div>

So, between the two div tags there is a 20px space.

But when there is a stack class inside a class stack, and set the --stack-gap individually, then the parent --stack-gap property gets ignored as it set on the child stack. Like:

.stack > * + * {
  margin-top: var(--stack-gap);
}
<div class="stack" style="--stack-gap:20px">
  <div>
    <div>...</div>
    <div>...</div>
  </div>
  <div class="stack" style="--stack-gap:60px">
    <div>...</div>
    <div>...</div>
  </div>
</div>

Now, the inner stack class has a 60px margin top as it sets the --stack-gap to 60px, but the expected behavior would be 20px margin-top as I set the --stack-gap to 20px on the parent stack.

I fully understand why it is happening, I just would like to ask how could I solve this problem, so the --stack-gap property on the stack element only affects the child elements, but not itself?


Solution

  • Thank you for the answers, but i think ive found the simplest approach to this. I'll use grid and the grid-gap property(i would go with a column flex and the gap property but this is only implemented in firefox as of now). So i'll use the next class:

    .stack{
        display:grid;
        grid-gap:var(--stack-gap);
    }
    

    with this solution i can set the --stack-gap individually and there wont be any conflicts.