How to group the css selectors

Issue

:host([aspect-ratio='square']) img {
      aspect-ratio: var(--ratio-square);
    }
    :host([aspect-ratio='landscape']) img {
      aspect-ratio: var(--ratio-landscape);
    }
    :host([aspect-ratio='portrait']) img {
      aspect-ratio: var(--ratio-portrait);
    }
    :host([aspect-ratio='widescreen']) img {
      aspect-ratio: var(--ratio-widescreen);
    }
    :host([aspect-ratio='ultrawide']) img {
      aspect-ratio: var(--ratio-ultrawide);
    }
    :host([aspect-ratio='golden']) img {
      aspect-ratio: var(--ratio-golden);
    }

How can I make it to a single line? by reducing the duplicates of this code

Solution

I don’t think you can reasonably do this with a single line.

You could do simplify it with Sass/Scss:

$ratios: "square", "landscape", "portrait", "widescreen", "ultrawide", "golden";

@each $ratio in $ratios {
    :host([aspect-ratio='#{$ratio}']) img {
      aspect-ratio: var(--ratio-#{$ratio});
    }
}

Which generates the CSS:

:host([aspect-ratio='square']) img {
    aspect-ratio: var(--ratio-square);
}

:host([aspect-ratio='landscape']) img {
    aspect-ratio: var(--ratio-landscape);
}

:host([aspect-ratio='portrait']) img {
    aspect-ratio: var(--ratio-portrait);
}

:host([aspect-ratio='widescreen']) img {
    aspect-ratio: var(--ratio-widescreen);
}

:host([aspect-ratio='ultrawide']) img {
    aspect-ratio: var(--ratio-ultrawide);
}

:host([aspect-ratio='golden']) img {
    aspect-ratio: var(--ratio-golden);
}

Answered By – phuzi

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published