html - 在没有一堆不同的图像大小和媒体查询的情况下使图像具有响应性的更有效方法?

标签 html css responsive-design

我正在一个响应式网站上工作,到目前为止,除了 Logo ( Logo 是 PNG 图像)之外,所有内容都是响应式的。我知道我可以使用媒体查询,但我已经意识到使用这种方法我需要不同尺寸的同一图像的多个版本。有没有更有效的方法来完成这个?此外,如果媒体查询是唯一的选择,我应该将它们制作成什么样的尺寸,以便我的网站在所有设备上看起来都不错。感谢所有的帮助!

我唯一尝试过/能想到的另一件事是使用 % 作为背景,但它在移动设备上仍然显示为垂直拉伸(stretch)。

  <div id="imgLogoDiv">
    <img id="imgLogo" src="/img/giphylogo_V1.png" alt="unable to load image">
  </div> 
#imgLogoDiv {
    display: flex;
    justify-content: center;
    height: auto;
}

#imgLogoDiv #imgLogo {
    width: 45%;
    height: auto;
    /*to make responsive use a % for width not px*/
}

@media (min-width: 320px) and (max-width: 480px) {

    body {
        background-image: url(img/mobileBackground.jpg);
        background-position: top center;
        background-size: cover;
        background-repeat: no-repeat;
    }
    /*This looks a bit better but there might be a better method.*/
    #imgLogoDiv #imgLogo {
        content: url("img/mobileLogo.png");
    }
}

How website and logo looks on mobile

最佳答案

I understand I am able to use media queries but I have realized with this method I would need many versions of the same image with different sizes.

这里几乎没有其他选项。

选项 1:使用通用样式。 Bootstrap 使用类 img-fulid使图像适合任何视口(viewport)

.img-fluid {
    max-width: 100%;
    height: auto;
}

例如:<img src='gify.gif' class='img-fluid' />

选项 2:杠杆 sizessrcset图像的属性。所以你可以避免使用大量的媒体查询

<img srcset="elva-fairy-320w.jpg 320w,
             elva-fairy-480w.jpg 480w,
             elva-fairy-800w.jpg 800w"
     sizes="(max-width: 320px) 280px,
            (max-width: 480px) 440px,
            800px"
     src="elva-fairy-800w.jpg" alt="Elva dressed as a fairy"> 

更多阅读 here

enter image description here

enter image description here

关于html - 在没有一堆不同的图像大小和媒体查询的情况下使图像具有响应性的更有效方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57878576/

相关文章:

html - 显示未在客户端定义的字体,仅在服务器上定义

css - Bootstrap SM Size 下一行的一些元素

html - 没有javascript的窗口分辨率处理

html - 右侧白色 block (html外)

javascript - jQuery.fadeIn 和 fadeOut 的 CSS3 替换

mobile - Bootstrap 3 的响应式日历

html - 使用 CSS 创建多个向外的边框半径

javascript - 禁用 Opera 的 Ctrl-Click 以编程方式保存图像?

javascript - Onclick 函数在外部 javascript 文件中不起作用

css - 如何更改以下代码中文本的颜色?