Search code examples
csssassnestedmixins

Is it better to use mixins or combined sets of styles in stylesheets?


I would like to know which way of coding stylesheets is better in terms of performance, readability and everyday use case.

Let's say we want to make styles:

.container {
  background-color: red;
  .nested-container {
    color: blue;
  }
}

.container-two {
  background-color: black;
  .nested-container {
    color: blue;
  }
}

I wonder which way is more efficient for this kind of case.

/* mixins way */
@mixin duplicated-container {
  .nested-container {
      color: blue;
  }
}

.container {
  background-color: red;
  @include duplicated-container;
}
.container-two {
  background-color: black;
  @include duplicated-container;
}

/* combined sets way */
.container {
    background-color: red;
}
.container-two {
    background-color: black;
}
.container,
.container-two {
  .nested-container {
    color: blue;
  }
}

First way is much more readable, at least for me. Second way makes output file smaller than when using mixins, because code is not duplicated in any way.

Please keep it in mind that this is just very simple example of what i want to achieve, if container and container-two are in two different places in file, first way makes it very readable and easy to play with, but it duplicates code in final output, so i'm not sure if it is good to use mixins this way.

This has been big dilemma for me for last few days and i decided to ask professionals for help, because I always end up with messy stylesheets. I appreciate all help.


Solution

  • The first seems like a better choice, since classes are listed in a single place.

    With the second approach, once you add a .container-three you'd have to remember to also add it to the list of classes under which .nested-container is gettings its styles from.

    You should not worry about the filesize when using mixins. With a modern pipeline of CSS minifier and gzipped content being default for most servers, duplicating content in CSS does not significantly increase the filesize, and might even perform better.

    Do not worry about duplicating code. It's a micro-optimisation that would be heavily optimised by gzip anyway. Go for readability in this case.