Question

I am trying on my latest project, opt in typography. It's working well so far. I have my base .typography class below:

.typography
  a
    @extend .link

  i, em
    @extend .italic

  b, strong
    @extend .bold

  h1, .h1
    @extend .h1

  h2, .h2
    @extend .h2

  h3, .h3
    @extend .h3

  h4, .h4
    @extend .h4

  h5, .h5
    @extend .h5

  h6, .h6
    @extend .h6

  p, ul, ol, pre, address
    @extend .block-margins

  ul
    @extend .unordered-list

  ol
    @extend .ordered-list

  pre, code
    @extend .fixed

I then just apply that to the parent element of any block i'd like to be styled like that.

My problem comes when, for example, I get to a p that needs to be opted in and it seems a bit overkill to wrap a <div class="typography"> ... </div around it just to opt it in. I would prefer to just add the .typography class to the <p> directly.

Is there any sass trickery I can use to alter my current typography class to allow it to work as is but also when I apply the typography class to any element within. So I basically need:

.typography
  p
    [STYLES]

and

p.typography
  [SAME STYLES]

Any thoughts on this?

Était-ce utile?

La solution

This is probably slightly more verbose than you're hoping for on the Sass side, but its the best you're going to get:

%link {
  color: blue;
}

%block-margins {
  margin: 1rem 0;
}

@mixin typography {
  &.typography, .typography & {
    @content;
  }
}

a {
  @include typography {
    @extend %link;
  }
}

p, ul, ol, pre, address {
  @include typography {
    @extend %block-margins;
  }
}

Output:

a.typography, .typography a {
  color: blue;
}

p.typography, .typography p, ul.typography, .typography ul, ol.typography, .typography ol, pre.typography, .typography pre, address.typography, .typography address {
  margin: 1rem 0;
}

Autres conseils

To make it at least a but reausable and not repeat code, you should define your styles as:

.typography
  a
    @extend .link
  ...

and then add the others by using previous ones:

a.typography
  @extend .typography a
...

By doing this you'd at least have a single point of maintenance even though your styles will be duplicated.

I wouldn't consider it a perfect solution, but one way to make it work could be to re-assign your styles:

p, ul, ol, pre, address {
  &.typography {
    @extend .block-margins;
  }
}

Might work until you find a better solution which does not produce duplicate code.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top