[csswg-drafts] Composing class names inside media queries (#4040)

OliverJAsh has just created a new issue for https://github.com/w3c/csswg-drafts:

== Composing class names inside media queries ==


I have some styles inside a class which can be used standalone, but I would also like to apply these styles to another class when a media query condition is met.

The only way to achieve this today (IIUC) is by either duplicating the styles for my classes, or moving the media queries into JavaScript and conditionally applying the classes there. Both of these are significant trade offs, so I believe there should be some way of achieving this in CSS, natively.

Below is an example.

I have two classes: `light` and `dark`.

```css
.light {
  border: 1px solid;
  background-color: white;
}

.dark {
  border: 1px solid black;
  background-color: black;
  color: white;
}
```

```html
<h2>light</h2>
<div class="light">foo</div>
<h2>dark</h2>
<div class="dark">foo</div>
```

Now I want to compose these class names to create a new version: light on mobile (i.e. narrow screens), dark on desktop (i.e. wide screens).

The only way I'm aware of doing this is by duplicating my styles:

```css
@media (max-width: 499px) {
  .lightOnMobileAndDarkOnDesktop {
    border: 1px solid;
    background-color: white;
  }
}

@media (min-width: 500px) {
  .lightOnMobileAndDarkOnDesktop {
    border: 1px solid black;
    background-color: black;
    color: white;
  }
}
```

```html
<h2>light on mobile, dark on desktop</h2>
<div class="lightOnMobileAndDarkOnDesktop">foo</div>
```

However I would like to achieve this without duplicating the styles for my classes, and without JavaScript.

Here is some pseudo code which illustrates what I would like to achieve:

```css
@media (max-width: 499px) {
  .lightOnMobileAndDarkOnDesktop {
    @extend .light;
  }
}

@media (min-width: 500px) {
  .lightOnMobileAndDarkOnDesktop {
    @extend .dark;
  }
}
```

Are there any proposals for CSS that would allow me to achieve this in the future?

Proposals I'm aware of which could help:

- [`@extend`](https://tabatkins.github.io/specs/css-extend-rule/), but this seems inactive. Last updated in 2015? What's the status of this now?
- [`@apply`](http://tabatkins.github.io/specs/css-apply-rule/), but this was abandoned.

(Originally posted to https://stackoverflow.com/questions/56628123/css-composing-class-names-inside-media-queries.)

Please view or discuss this issue at https://github.com/w3c/csswg-drafts/issues/4040 using your GitHub account

Received on Tuesday, 18 June 2019 10:48:36 UTC