我正在尝试使用媒体查询根据屏幕大小更改图像 src。我试过 background: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>
在这种情况下,“BigImage”将在设备宽度超过 900 像素时显示。大于 480 像素时为“MediumImage”,小于 480 像素时为“OtherImage”。如果您使用“max-width: 900px”而不是 min-width,当宽度超过 900px 时它也会显示。
希望对您有所帮助!
关于html - 根据屏幕大小更改图像 src,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30460681/