Domanda

I'm creating a SASS mixin library for my team to use in CSS classes of their choosing. I'm realizing that preventing style contamination is more difficult than I thought.

Without a preprocessor it's easy for me to separate these two styles

.button { color: red; }
.link { color: blue; }

Now, I want to create mixins for each style

@mixin button()
  color: red

@mixin link()
  color: blue

Seems simple enough, but I have no control over how the mixins will be assigned to classes. The user may choose to do this:

SASS

.btn
  @include button()

ul.nav > li > a
  @include link()

HTML

<ul class="nav">
  <li>
    <a href="">Home</a>
  </li>
  <li>
    <a class="btn" href="">Save</a>
  </li>
</ul>

Now the button inherits the link styles. Of course, there are a few things I can do with the CSS to "fight" this inheritance, but I'm interested more in an overall technique to namespace mixin styles (if possible).

È stato utile?

Soluzione

Having worked on this for a while (long before posting this question), I'll post my own administrative workaround, if not a total solution:

Enforce in your styleguide that naked element selection (e.g. "div {...}) is not allowed. Users will need to do as such:

SASS

@mixin button()
  color: red

@mixin link()
  color: blue

.btn
  @include button()

ul.nav > li > a.nav-link
  @include link()

Unfortunately, this adds more classes to the HTML.

Update

I came to hate the above method. Direct descendent selectors all over the place tightly couple the proximity of elements.

The cleanest way I can think to solve this problem is to eschew content-descriptive classes for elements (as opposed to blocks.)

After all, Blocks like navbars and modals can mean all kinds of things, but what other class do you need to describe a button? Perhaps mixins on the button should be deferred to modifiers on the button.

.button
  // This has already been defined by the underlying framework.

.button.send-form
  @include button-primary()
  // This is a special button so we'll move in the primary color and a drop shadow.
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top