仅当浏览器宽度大于 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);}}
但是我担心如果窗口恰好是 8:5,用户将不得不下载两个图像。
如能提供有关如何确保只加载一张图片的任何帮助,我们将不胜感激,谢谢
最佳答案
经过一些测试,事实证明您不需要更改任何东西:
@media (min-aspect-ratio: 8/5) {...}
@media (max-aspect-ratio: 8/5) {...}
我做了一个演示。以全尺寸打开它并调整浏览器的大小。它们永远不会相同(真或假)。
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: 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;
}
.\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;
}
}
<div class="100%">
<div class="50%">
</div>
</div>
在全宽测试以上内容并将浏览器窗口设置为正好 800px x 500px
时,它显示 not above 8/5
和 below 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 中的最后一个,就是在两个条件都为真时应用的那个,如果它们同时为真的话。
关于html - 独家宽高比媒体查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34381089/