csssassless

Is there a way to assign the same value to 2 css properties at once?


Using CSS, LESS, or Sass can you assign the same value to 2 css properties at once?

Just like:

.c1, c2 {sameValue}

But instead like this:

.c2 { background-color:, color: sameValue}

Solution

  • Update for LESS v3.0.0 and CSS Custom Properties

    CSS

    CSS variables are supported in all major browsers and most many browsers (ref: caniuse).

    See zzzzBov's answer for an example.

    Less v3+

    Since 2017, LESS can look up a property:

    .demo {
      background-color: red;
      color: $color;
    }
    

    See the docs for details.


    Original answer

    CSS

    You can't do this with CSS.

    LESS, Sass

    The easiest way to do this is use a variable. Here's how you'd do that in LESS

    @color: red;
    .demo {
      background-color: @color;
      color: @color;
    }
    

    and the same thing in Sass

    $color: red;
    .demo {
      background-color: $color;
      color: $color;
    }
    

    But you can also achieve the power you want. Here's one way you could do it in LESS:

    .properties(@properties, @value, @i: 0) when (@i < length(@properties)) {
      @property: extract(@properties, @i + 1);   // get the property
      @{property}: @value;                       // write the style
      .properties(@properties, @value, (@i + 1)) // loop
    }
    
    .demo {
      @props: background-color, color;
      .properties(@props, red)
    }
    

    will compile to your desired

    .demo {
      background-color: red;
      color: red;
    }
    

    How's it work?


    Note that @props could be defined within .test, as above, or anywhere where .test will have access to it, and same for the value. You might end up with

    @props: background-color, color;
    @val: red;
    @val2: green;
    .properties {...}
    .demo {
      border-color: @val2;
      .properties(@props, @val)
    }
    .demo2 {
      .properties(@props, @val2)
    }