cssnested

How to declare ::before once and for and add separate content based on classes in nested css declaration syntax?


Having below HTML

.legend__list {
  display: flex;
  border: 2px solid rgb(241, 230, 230);
  align-content: center;

  .legend {
    font-size: large;
    color: greenyellow;

    &.clan {
      &::before {
        content: "\1F9EC";
      }
    }

    &.deity {
      &::before {
        content: "\1FA94";
      }
    }

    &.cast {
      &::before {
        content: "\4DE4";
      }
    }
  }
}

dl {
  display: flex;
  margin: auto;
}
<div class="legend__list">
  <dl>
    <dt class="legend clan"></dt>
    <dd>Clan</dd>
  </dl>
  <dl>
    <dt class="legend deity"></dt>
    <dd>Deity</dd>
  </dl>
  <dl>
    <dt class="legend cast"></dt>
    <dd>Cast</dd>
  </dl>
</div>

This is working fine but looking for alternative or shorter syntax somehow :has, :is or :where ?

mock code

is there any way we can achieve this?

.legend {
  font-size: large;
  color: greenyellow;

  &::before {
    content: "";

    :has(.deity) {
      content: "\1F9EC";
    }

    :where(.clan) {
      content: "\1FA94";
    }

    :is(.cast) {
      content: "\4DE4";
    }
  }

Solution

  • A perfect use case for data attribute

    .legend__list {
      display: flex;
      border: 2px solid rgb(241, 230, 230);
      align-content: center;
      .legend {
        font-size: large;
        color: greenyellow;
        &::before {
          content: attr(data-icon);
        }
      }
    }
    
    dl {
      display: flex;
      margin: auto;
    }
    <div class="legend__list">
      <dl>
        <dt class="legend" data-icon="&#x1F9EC"></dt>
        <dd>Clan</dd>
      </dl>
      <dl>
        <dt class="legend" data-icon="&#x1FA94"></dt>
        <dd>Deity</dd>
      </dl>
      <dl>
        <dt class="legend" data-icon="&#x4DE4"></dt>
        <dd>Cast</dd>
      </dl>
    </div>