我正在尝试使用媒体查询根据屏幕尺寸更改图像 src。我尝试过背景:url(x);但它不起作用。我在某处读到我应该使用 content:url(x) 代替,但是当我这样做时,我得到一个空白页面。谁能告诉我我的代码有什么问题吗?
HTML:
<div class="container" id="at-header">
<img class="image" id="logo" src="img/logo_white.png" />
<img class="image" id="main-img" src="img/desktop_homepage.jpg" />
</div>
CSS:
@media screen and (max-width: 767px){
#main-img{
content:url("img/mobile_homepage.jpg");
}
}
@media screen and (min-width: 768px) {
#main-img{
content:url("img/tablet_homepage.jpg");
}
}
@media (min-width: 992px){
#main-img{
content:url("img/desktop_homepage.jpg");
}
}
@media (min-width: 1200px) {
#main-img{
content:url("img/desktop_homepage.jpg");
}
}
这对我有用。我不知道你是否熟悉这个标签,但它甚至不需要 CSS。
<picture>
<source media="(min-width: 900px)" srcset="BigImage.png">
<source media="(min-width: 480px)" srcset="MediumImage.png">
<img src="OtherImage.png" alt="IfItDoesntMatchAnyMedia">
</picture>
在这种情况下,当设备宽度超过 900 像素时,将显示“BigImage”。如果超过 480 像素,则为“MediumImage”;如果小于 480 像素,则为“OtherImage”。如果您使用“max-width: 900px”而不是 min-width,那么当宽度超过 900px 时它也会显示。
希望能帮助到你!
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)