SemperCallide
SemperCallide

Reputation: 2070

How to share styling rules between nested classes using LESS?

I have three CSS classes that share a number of properties: cell-empty, cell-record-left and cell-record-right.

This is the CSS I want to ultimately produce:

.cell-empty {
   background-color: red; //shared between all cells
   border: 1px solid black;
}

.cell-record-left {
    background-color: red; //shared between all cells
    text-indent: 15px; //shared between both .cell-record-left & .cell-record right
    border-right: 1px solid #DFE5ED;
}

.cell-record-right {
    background-color: red; //shared between all cells
    text-indent: 15px; //shared between both .cell-record-left & .cell-record right
    border-left: 1px solid #DFE5ED;
}

So I thought I would use LESS to simplify my classes, using nesting. This was what I first produced:

.cell {
    background-color: red; 

    &-empty {
      border: 1px solid black;
    }

    &-record {
      text-indent: 15px;

      &-left {
        border-right: 1px solid #DFE5ED;
      }

      &-right {
        border-left: 1px solid #DFE5ED;
      }
   }
}

However that didn't work, because I was assuming nesting would inherit rules (which, obviously, it does not). So I tried again, this time using mixins, like so:

.cell {
    background-color: red; 

    &-empty {
      border: 1px solid black;
      .cell;
    }

    &-record {
      text-indent: 15px;

      &-left {
        border-right: 1px solid #DFE5ED;
        .cell;
        .cell-record;
      }

      &-right {
        border-left: 1px solid #DFE5ED;
        .cell;
        .cell-record;
      }
   }
}

However that does not seem to be working either. When I look at the computed CSS (using this site: http://less2css.org/) I receive errors that the mixin classes I am using are not defined.

So, I am confused. What can I do with LESS to simplify my CSS, so that I am not re-writing the same styling over and over again?

I appreciate any help very much. Thank you!

Upvotes: 0

Views: 219

Answers (1)

Brad
Brad

Reputation: 8668

I think the problem you are getting with the mixin solution is that you are using the mixin within the definition of the mixin.

you need to finish defining the mixin before you use it, like this:

LESS:

.cell {
  background:red;
}

.cell-empty {
  .cell
}

The css output would be:

.cell {
  background: red;
}
.cell-empty {
  background: red;
}

Upvotes: 2

Related Questions