【问题标题】:How to fit background image in all screen sizes?如何使背景图像适合所有屏幕尺寸?
【发布时间】:2022-01-21 23:51:41
【问题描述】:

我的背景图片有问题。不知何故,在大屏幕上,头部被切断以适应屏幕。有没有办法确保无论屏幕大小如何,始终呈现 100% 的图片? background-size 的初始属性是cover,但是当以这种方式设置时,图像的顶部会被切割以适合容器。当我按照下面将背景大小更改为 100% 100% 时,我得到了我想要的结果,但图像的质量受到了影响。有没有办法解决这个问题。我审查了大多数与背景图像相关的文档,但没有一个能给我想要的结果。 html 和 body 的高度/宽度都设置为 100%。

提前感谢您的帮助。 狮子座

.main .masthead {
    min-height: 100%;
    padding-top: 7.5rem;
    padding-bottom: 7.5rem;
    text-align: center;
    color: #fff;
    background: -webkit-gradient(linear, left top, left bottom, from(rgba(92, 77, 66, 0.8)), to(rgba(92, 77, 66, 0.8))), url(/_next/static/media/dr.cut_thebarbershow_blue.4a28589b.jpg);
    background: linear-gradient(to bottom, rgba(92, 77, 66, 0.8) 0%, rgba(92, 77, 66, 0.8) 100%), url(/_next/static/media/dr.cut_thebarbershow_blue.4a28589b.jpg);
    background-repeat: no-repeat;
    background-attachment: scroll;
    background-position: center center;
    background-size: 100% 100%;
    z-index: 1;
    width: 100vw;
}

sandbox

【问题讨论】:

  • 我想你最好的选择是留下background-size: cover;并根据图像更改位置background-position: center top
  • 来自 MDN 站点:Cover 在不拉伸图像的情况下尽可能大地缩放图像。如果图像的比例与元素不同,则会垂直或水平裁剪它,以便没有空白空间。 我会说最好的选择是将其保留为 cover 并更改 background-position 否则,为移动设备使用不同的图像。
  • 感谢@MattHamer5 抽出宝贵时间。它不起作用

标签: html css bootstrap-4 sass background-image


【解决方案1】:

最好在你的主 CSS 文件中有以下设置,以默认删除所有周围的空格

body,
::after,
::before {
  box-sizing: border-box !important;
  padding: 0px !important;
  margin: 0px !important;
}
然后考虑以下身体样式:

body {
  background-repeat: no-repeat;
  background-size: cover;
  background: -webkit-gradient(linear, left top, left bottom, from(rgba(92, 77, 66, 0.8)), to(rgba(92, 77, 66, 0.8))),
    url(/_next/static/media/dr.cut_thebarbershow_blue.4a28589b.jpg);
  background: linear-gradient(to bottom, rgba(92, 77, 66, 0.8) 0%, rgba(92, 77, 66, 0.8) 100%),
    url(/_next/static/media/dr.cut_thebarbershow_blue.4a28589b.jpg);
}

如果您的图像质量下降,请下载您的图像并使用 Photoshop 或其他工具来保持图像质量。

【讨论】:

    【解决方案2】:

    为了使背景图像适合屏幕大小,我们可以设置 background-size 属性来包含。将背景大小设置为包含;它告诉浏览器图像缩放以适应内容区域而不会丢失其纵横比

    要了解更多信息,请参阅提供的链接: https://www.bitdegree.org/learn/responsive-image#setting-background-size-to-fit-screen

    【讨论】:

    • 嗨@pooja 感谢您花时间向桑杰解释我已经尝试了你们推荐的所有方法,但它不起作用。我设置了一个沙箱来显示问题,也许它可以让您更好地了解问题。再次感谢kids8.sse.codesandbox.io
    【解决方案3】:

    您应该在媒体查询中使用 cover 或 auto,这样它将根据屏幕尺寸覆盖整个区域。

    background-repeat:no-repeat;
    background-size:cover;
    

    【讨论】:

    • 非常感谢您抽出宝贵时间,我已经尝试了您推荐的方法,但效果不如预期,我添加了一个沙箱链接,以便您可以在大屏幕上看到问题。 kids8.sse.codesandbox.io再次感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-06-29
    • 2019-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多