使背景图像适合浏览器的宽度,并在必要时扩展高度 [英] fit background image to browser width and expand height if necessary

查看:62
本文介绍了使背景图像适合浏览器的宽度,并在必要时扩展高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有纵向图像(宽度:869px;高度:2853px),我想将其用作网站的背景图像.图像应具有响应性,并始终占满浏览器窗口的整个宽度.图像应保持其比例,并且切勿裁切.因此,高度需要调整为给定的宽度.由于图像高度始终大于视口高度,因此您应该能够滚动到图像底部,该底部也应该是网站底部.

i have portrait image (width: 869px; height: 2853px) which i wanna use as the background image for my website. the image should be responsive and always fill the entire width of the browser window. the image should keep its proportions and should never be cropped. therefor the height needs to adjust to the given width. since the image height is always bigger than the viewport height, you should be able to scroll to the bottom of the image, which should be the bottom of the website as well.

如果有人告诉我该怎么做,我将非常感激.

i'd really appreciate if someone would tell me how to do this.

推荐答案

当其他评论者不断建议使用 background-size:封面时,我认为其他评论者无视您的请求而不是裁剪"图像.

I think the other commenters are ignoring your request for help in not "cropping" the image, when they keep suggesting use of background-size: cover.

以下是我对您的要求:

  • 要作为背景的图像,位于网站内容的后面.
  • 背景图像具有特定的长宽比,因此不应裁剪
  • 如果浏览器窗口与图像的宽高比不匹配,则应允许垂直滚动,但应始终适合窗口宽度.

仅适用于CSS的解决方案...

A css only solution...

body {
  position: relative;
  margin: 0;
}
body::before {
  content: '';
  display: block;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  z-index: -1;
  height: 0;
  /* height / width = ratio% */
  /* 2853px / 869px = 328.3084% */
  padding-bottom: 328.3084%;
  padding-bottom: calc(2853 / 869 * 100%);
  background: url('//placekitten.com/869/2853') center top / 100% auto no-repeat;
}

用图片的网址替换网址,如果图片的像素尺寸发生变化,请按照我已注释掉 padding-bottom 应该如何计算的方式进行更新.

Replace the url with the url of your image, and if the image pixel dimensions change, update those in the way I have commented out how padding-bottom should be calculated.

这将在网站正文中创建一个单独的背景元素,并且仍然允许您在网站内部拥有所需的任何内容.但是请记住,如果您的屏幕很小,例如320px/480px,并且由于屏幕的宽度狭窄,网站内容变得非常高,则可以滚动浏览此背景图像以说明内容.这不会破坏此代码,但是我只建议向您的html元素添加背景颜色或纹理,在这种情况下,该颜色或纹理将显示在图像下方.祝你好运.

This creates a separate background element inside the body of the website and still allows you to have whatever content you want inside your site. But keep in mind, if you're on a very small screen, say 320px/480px, and the websites content becomes very tall because of the narrow width of the screen, this background image could be scrolled passed to account for the content. That won't break this code, but I would just suggest adding a background color or texture to your html element, which would show below the image in this case. Good luck.

这篇关于使背景图像适合浏览器的宽度,并在必要时扩展高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆