Media query precedence can change unexpectedly
- Dominant language
- JavaScript
- Stars
- 5.3k
- Forks
- 187
- PR merge metrics
- No merged PRs in 30d
Description
This is a variation of the issue mentinoed in the [README](https://github.com/Khan/aphrodite#creating-extensions), 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"
},
},
});
```
```
box
```
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",
},
},
});
```
```
box
```
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](https://jsfiddle.net/n5u2wwjg/126836/) that illustrates the behavior. Adding and removing `fontWeightStyles` changes the background color of the box.
Contributor guide
No contributing guide indexed for this repository
Research direction
Start with the README section on creating extensions and reproduce the behavior in the linked JSFiddle using StyleSheet.create and css. Trace how media queries from backgroundStyles and fontWeightStyles are combined. Done means adding an unrelated style with differently ordered breakpoints no longer changes which media query determines the background color.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- css, javascript
- Domain
- frontend, web-dev
- Issue type
- Bug
- Difficulty
- 4/5
- Estimated time
- 3-5 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 43/100