0

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. Below is an example.

I have two classes: light and dark.

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

.dark {
    border: 1px solid black;
    background-color: black;
    color: white;
}
<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:

@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;
    }
}
<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:

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

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

If there isn't any way to achieve something to this effect today, my next question would be: are there any proposals for CSS that would allow me to achieve this in the future?

Oliver Joseph Ash
  • 3,138
  • 2
  • 27
  • 47
  • you could use sass (or another pre-processor) for this, otherwise the closest you would get with pure css is css variables, but I don't think it would do exactly what you want - see this: https://stackoverflow.com/questions/1065435/can-a-css-class-inherit-one-or-more-other-classes – Pete Jun 17 '19 at 09:19
  • with CSS variables I believe you can only assign property values to a variable, not a collection of values, so a preprocessor is probably the best option if you're avoiding js – metaDesign Jun 17 '19 at 09:25
  • Re. preprocessors, is that mixins? Unfortunately that would count as duplicating the styles. Perhaps we need mixin support in native CSS… – Oliver Joseph Ash Jun 17 '19 at 09:27

0 Answers0