Html @media 查询和图像交换
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27853884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
@media queries and image swapping
提问by Aarati Akkapeddi
I want the image in my site to completely change when the browser is resized.
我希望我的网站中的图像在浏览器调整大小时完全改变。
I've been using media-queries, but I can't seem to get it right. Any thoughts/tips?
我一直在使用媒体查询,但我似乎无法正确使用。任何想法/提示?
回答by jmore009
In the future please add code you've tried.
将来请添加您尝试过的代码。
if it's an image
tag you can use a class. Hide the second image on page load and show + hide image 1 at a certain screen size like so:
如果它是一个image
标签,你可以使用一个类。在页面加载时隐藏第二个图像,并在特定屏幕尺寸下显示 + 隐藏图像 1,如下所示:
HTML
HTML
<img src="image.jpg" class="image1"/>
<img src="image.jpg" class="image2"/>
CSS
CSS
.image2{
display: none;
}
@media only screen and (max-width: 500px){ //some value
.image1{
display: none;
}
.image2{
display: block;
}
}
OR
或者
If it's a background-image
you can simply swap the image:
如果是,background-image
您可以简单地交换图像:
HTML
HTML
<div class="example"></div>
CSS
CSS
.example{
background-image: url("example.jpg");
}
@media only screen and (max-width: 500px){ //some value
.example{
background-image: url("example2.jpg");
}
}
回答by ekfuhrmann
This can be done using the HTML5 picture
element which doesn't require CSS for changing img
elements on specified media queries. If you're intrested in this approach, do be aware of its browser supportwhich does NOTinclude IE, though there is a polyfillfor older browsers.
这可以使用 HTML5picture
元素来完成,该元素不需要 CSS 来更改img
指定媒体查询上的元素。如果你在这种方法intrested,你知道它的浏览器支持它确实不包括IE,虽然有一个填充工具旧版本浏览器。
<h1>Resize Window</h1>
<picture>
<source srcset="https://placehold.it/1400x1400" media="(min-width: 1400px)"/>
<source srcset="https://placehold.it/1200x1200" media="(min-width: 1200px)"/>
<source srcset="https://placehold.it/800x800" media="(min-width: 800px)"/>
<source srcset="https://placehold.it/600x600" media="(min-width: 600px)"/>
<img src="https://placehold.it/400x400" alt="example"/>
</picture>
回答by che-azeh
You can use the content
property to insert your image. However, images included like this could be difficult to style. (Run code snippet in full screen before resizing browser)
您可以使用该content
属性插入图像。但是,像这样包含的图像可能难以设计样式。(在调整浏览器大小之前全屏运行代码片段)
@media screen and (max-width: 479px) {
div img {
display:none;
}
div::before {
content: url("https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-icon.svg?v=6e4af45f4d66");
}
}
<p>Resize this window to see image change</p>
<div>
<img src="https://cdn.sstatic.net/Sites/stackoverflow/company/img/logos/so/so-logo.svg?v=2bb144720a66" width="200px" />
</div>