Skip to content Skip to sidebar Skip to footer

Exclusive Aspect Ratio Media Query

I want to have a picture at the side of my site only if the browser width is >1200 px, but I want to use one of two pictures depending on the aspect ratio. I suppose I need to u

Solution 1:

After a bit of testing, it turns out you don't need to change a thing:

@media (min-aspect-ratio: 8/5) {...}@media (max-aspect-ratio: 8/5) {...}

I made a demo. Open it in full size and resize the browser. They'll never be both the same (true or false).

body {margin: 0;}
.\31\30\30\25 {
  display: flex;
  min-height: 100vh;
  background-color: #eee;
  justify-content: center;
}
.\35\30\25 {
  flex-basis: 50%;
  min-height: 50vh;
  border: 1px solid #eee;
  background-color: #fff;
  align-self: center;
  box-shadow: 01px5px0rgba(0,0,0,.2),02px2px0rgba(0,0,0,.14),03px1px -2pxrgba(0,0,0,.12);
  position: relative;
}
.\35\30\25:before, .\35\30\25:after  {
  padding: 20px;
  background-color: rgba(255,255,255,.75);
  border: 1px solid white;
  position: absolute;
  width: calc(25vw - 40px);
  box-sizing: border-box;
  color: red;
}
.\35\30\25:before {
  right: calc(100% + 20px);
  transform: translateY(-50%);
  content: 'not above 8/5';
  text-align: right;
}

.\35\30\25:after {
  left: calc(100% + 20px);
  bottom: 0;
  transform: translateY(50%);
  content: 'not below 8/5'
}
@media (min-aspect-ratio: 8/5){
  .\35\30\25:before {
    content: 'above 8/5';
    color: black;
  }  
}
@media (max-aspect-ratio: 8/5){
  .\35\30\25:after {
    content: 'below 8/5';
    color: black;
  }  
}
<divclass="100%"><divclass="50%"></div></div>

While testing the above in full width and setting browser window to be exactly 800px x 500px it says not above 8/5 and below 8/5. I tested it in IE10, FF and Chrome.

However, if you want to make extra sure that only one applies, you don't have to rely on browsers. Even if both conditions are ever true, if you modify the same property of the same element for both media queries, only one will apply:

@media (min-aspect-ratio: 8/5) {
    [same-selector] {
        [same-property]: [some-value];
    }
}
@media (max-aspect-ratio: 8/5) {
    /* 
     * This one will apply if both media conditions are ever true.
     * If you want the other one, place that media query below this one.
     */[same-selector] {
        [same-property]: [different-value]; 

    }
}

If two rules apply on the same property of the same element, the one with the stronger selector applies or, if the selector is identical, the last one parsed by CSS applies. And there you have it! The last one you place in CSS, that's the one that applies when both conditions are true, if they ever are true simultaniously.

Post a Comment for "Exclusive Aspect Ratio Media Query"