独家宽高比媒体查询

Exclusive Aspect Ratio Media Query

我只想在浏览器宽度大于 1200 像素时在我的网站旁边放一张图片,但我想根据宽高比使用两张图片中的一张。我想我需要使用

  @media all and (min-width: 1201px)  and (min-aspect-ratio: 8/5){
#div {background-image:url(pic1.jpg);}}
@media all and (max-width: 1201px)  and (max-aspect-ratio: 8/5){
#div {background-image:url(pic2.jpg);}}

不过我担心如果 window 恰好是 8:5,用户将不得不下载两个图像。

如能提供有关如何确保只加载一张图片的帮助,我们将不胜感激,谢谢

经过一些测试,事实证明您不需要更改任何东西:

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

我做了一个演示。以全尺寸打开它并调整浏览器的大小。它们永远不会相同(真或假)。

body {margin: 0;}
. {
  display: flex;
  min-height: 100vh;
  background-color: #eee;
  justify-content: center;
}
. {
  flex-basis: 50%;
  min-height: 50vh;
  border: 1px solid #eee;
  background-color: #fff;
  align-self: center;
  box-shadow: 0 1px 5px 0 rgba(0,0,0,.2),0 2px 2px 0 rgba(0,0,0,.14),0 3px 1px -2px rgba(0,0,0,.12);
  position: relative;
}
.:before, .: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;
}
.:before {
  right: calc(100% + 20px);
  transform: translateY(-50%);
  content: 'not above 8/5';
  text-align: right;
}

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

在全角测试以上内容并将浏览器 window 设置为 800px x 500px 时,它显示 not above 8/5below 8/5。我在 IE10、FF 和 Chrome.

中测试了它

但是,如果您想特别确保只有一个适用,则不必依赖浏览器。即使两个条件都为真,如果您为两个媒体查询修改相同元素的相同 属性,则只有一个适用:

@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]; 

    }
}

如果两个规则应用于同一元素的相同 属性,则应用具有更强选择器的规则,或者,如果选择器相同,则应用由 CSS 解析的最后一个。你有它!您放在 CSS 中的最后一个,即当两个条件都为真时应用的那个,如果它们同时为真。