aphrodite icon indicating copy to clipboard operation
aphrodite copied to clipboard

Media query precedence can change unexpectedly

Open scott-silver opened this issue 7 years ago • 0 comments

This is a variation of the issue mentinoed in the README, but it applies to media queries as well and can create some unexpected behaviors.

Say you've got some styles that determine an element's background color based on screen width:

const backgroundStyles = StyleSheet.create({
  box: {
    [`@media (min-width: 1px)`]: {
      backgroundColor: "red"
    },
    [`@media (min-width: 2px)`]: {
      backgroundColor: "blue"
    },
  },
});
<div className={css(backgroundStyles.box)}>
  box
</div>

The background of the box will be blue (assuming you're viewing it at a screen width greater than 2 pixels). Both styles are being applied to the element (since your screen width is greater than 1px and greater than 2px), but the second media query style takes precedence because it was defined last.

But if you add separate styles that define behavior at the same media breakpoints, but with a different ordering, you will change the ordering of all media queries:

const fontWeightStyles = StyleSheet.create({
  box: {
    [`@media (min-width: 2px)`]: {
      fontWeight: "400",
    },    
    [`@media (min-width: 1px)`]: {
      fontWeight: "300",      
    },
  },
});
<div className={css(backgroundStyles.box, fontWeightStyles.box)}>
  box
</div>

The background color of the box is now red.

Aphrodite has combined the styles defined in each media query, but reordered them to reflect the order defined in fontWeightStyles.

@media (min-width: 1px) {
  ._1s7o9eql {
    background-color: red !important;
    font-weight: 300 !important;
  }
}

@media (min-width: 2px) {
  ._1s7o9eql {
    background-color: blue !important;
    font-weight: 400 !important;
  }
}

Here's a JSFiddle that illustrates the behavior. Adding and removing fontWeightStyles changes the background color of the box.

scott-silver avatar Aug 07 '18 22:08 scott-silver