Home > Blockchain >  CSS aspect-ratio media queries with no overlapping?
CSS aspect-ratio media queries with no overlapping?

Time:09-27

I'm trying to toggle 1:1 and 16:9 <video> elements using display block/none and aspect-ratio-media queries, but can't figure out how to eliminate potential AR overlap.

Here is my CSS and there is [theoretically] overlap when the AR is exactly 4/3. That said, I don't ever see both videos using these queries, but I'm concerned a client with exactly a 4/3 AR will show both videos.

@media (min-aspect-ratio: 4/3) {
  video.mobile {
    display: none;
  }

  video.desktop {
    display: block;
  }
}

@media (max-aspect-ratio: 4/3) {
  video.mobile {
    display: block;
  }

  video.desktop {
    display: none;
  }
}

CodePudding user response:

Yes, you are right! The conditions of both media queries will be met at an exact aspect ratio of 4:3.

The cascading nature of CSS, however, plays to our advantage here. The styles declared in the latter media query will overwrite anything declared in the former media query.

This means at an exact aspect ratio of 4:3, video.desktop { display: none; } from the latter media query will be applied and thus hide the desktop version of your video.

To test the aspect ratio for yourself, run the following code snippet in full page view, launch the Device Toolbar in Chrome DevTools and set viewport dimensions to 640x480.

div {
    display: block;
    width: 300px;
    height: 200px;
    background: silver;
}

@media (min-aspect-ratio: 4/3) {
    .mobile {
        background: lime;
    }
}

@media (max-aspect-ratio: 4/3) {
    .desktop {
        background: lime;
    }
}
<div ></div>
<div ></div>

  • Related