css html上的媒体查询

vxbzzdmp  于 2023-04-01  发布在  其他
关注(0)|答案(4)|浏览(161)

有没有一种方法可以在html上使用媒体查询?我需要在我的页面上集中放置一个像横幅一样的图像,当屏幕小于768px时,它会显示一个较小的图像,但当屏幕增长到超过768px时,它应该将较小的图像替换为另一个更大的图像。有没有一种方法可以只在html和内联css上实现这个功能?我不应该使用外部文件。

svujldwt

svujldwt1#

你可以使用内联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>
q7solyqu

q7solyqu2#

你可以使用一个div,它有一个background-image而不是img元素。然后你可以在CSS中添加一个媒体查询,在那里你为移动的版本定义一个较小的大小和一个不同的background-image

7ajki6be

7ajki6be3#

如果你必须在一个文件中做,在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>
toe95027

toe950274#

你甚至不需要使用CSS,使用<picture>元素;它是现代浏览器的widely supported

<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>

相关问题