有没有办法在 html 上使用媒体查询?我需要在我的页面上放置一个像横幅一样的图像,当屏幕小于 768px 时它显示较小的图像但是当屏幕增长到超过 768px 时它应该将较小的图像替换为我拥有的另一个更大的图像.有没有办法只在 html 和内联 css 上做这个?我不应该使用外部文件。
您可以使用内联 CSS 实现此目的:
<div style="text-align: center;">
<img src="small-banner.jpg" alt="Small Banner" style="max-width: 100%;">
<style>
@media (min-width: 768px) {
img {
content: url(large-banner.jpg);
}
}
</style>
</div>
您可以使用具有
div
的 background-image
代替 img
元素。然后您可以在 CSS 中添加一个媒体查询,您可以在其中为移动版本定义较小的尺寸和不同的background-image
。
如果你必须在一个文件中做,在html中,不可能在img标签中做。但是你可以做这样的事情,使用嵌入式样式元素。例如:
<html>
...
<style>
.large-img {
display: none;
}
.small-img {
display: block;
}
@media(min-width: 768px) {
.large-img {
display: block;
}
.small-img {
display: none;
}
}
</style>
<body>
...
<img class="large-img" src="largeImage.png">
<img class="small-img" src="smallImage.png">
...
</body>
</html>
<picture>
元素;它被现代浏览器广泛支持:
<picture>
<source
srcset="path/to/bigger/picture"
media="(min-width: 768px)"
>
<img src="path/to/smaller/picture">
</picture>
试试看:
<picture>
<source
srcset="https://picsum.photos/700"
media="(min-width: 768px)"
>
<img src="https://picsum.photos/400">
</picture>