yuheijotaki.com

Sass の `map-get`

例えば、

<div class="object object_01"><amp-img src=""></amp-img></div>
<div class="object object_02"><amp-img src=""></amp-img></div>
<div class="object object_03"><amp-img src=""></amp-img></div>
<div class="object object_04"><amp-img src=""></amp-img></div>
<div class="object object_05"><amp-img src=""></amp-img></div>
...

のような HTML があって、

.object {
  &.object_01 {
    top: 240px;
    bottom: 120px;
    width: 80px;
    height: 40px;
    amp-img {
      width: 80px;
      height: 40px;
    }
  }
  &.object_02 {
  ...
}

のような CSS を書きたいとき、SCSS で map-get を用いると、

.object {
  $objectList: (
    object_01: (
      object-top: 240px,
      object-right: 120px,
      object-width: 80px,
      object-height: 40px
    ),
    object_02: (
      object-top: 160px,
      object-right: 220px,
      object-width: 20px,
      object-height: 100px
    ),
    ...
  );
  @each $objectNum, $property in $objectList {
    &.#{$objectNum} {
      top: map-get($property, object-top);
      right: map-get($property, object-right);
      bottom: map-get($property, object-bottom);
      left: map-get($property, object-left);
      width: map-get($property, object-width);
      height: map-get($property, object-height);
      amp-img {
        width: map-get($property, object-width);
        height: map-get($property, object-height);
      }
    }
  }
}

とすると連想配列的な配列を処理できる。
少し冗長な気もしますが、、

参考