缩放或裁剪背景图像而不是拉伸它

时间:2016-03-10 13:29:40

标签: javascript jquery html css image

我有一个背景图片,它占据浏览器窗口的整个宽度。 此背景图像应具有固定的高度,例如500 px。

当我的宽高比接近浏览器窗口时,我试图让这个图像尽可能完整,然后缩放或裁剪一个部分 当浏览器窗口变大时,图像(例如中间)而不是拉伸它或仅显示它的一侧。

以下是我想要获得的一个例子:

enter image description here

以下是当前工作原理的小提琴:https://jsfiddle.net/bb61c412/

这是当前的HTML代码:



<!DOCTYPE html>
<html lang="en">

<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://bootswatch.com/bower_components/bootstrap/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://bootswatch.com/cosmo/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>

<body>
  <div class="navbar navbar-default navbar-fixed-top ">
    <div class="container">
      <div class="navbar-header">
        <a href="#" class="navbar-brand">website</a>
        <button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#navbar-main">
          <span class="icon-bar"></span>
        </button>
      </div>
    </div>
  </div>


  <div style="width:100vw; height: 500px; background-image: url(https://upload.wikimedia.org/wikipedia/commons/8/80/Paul_Gauguin_088.jpg); background-repeat: no-repeat;">
  </div>
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:1)

添加background-size:cover即可

https://jsfiddle.net/bb61c412/1/

答案 1 :(得分:1)

正如@theblackgigant所说,你必须将background-size属性设置为'enter code here封面。 您还可以将background-position: bottom center设置为具有正确的行为 https://jsfiddle.net/bb61c412/2/

答案 2 :(得分:1)

您的代码应该是这样的:

<!DOCTYPE html>
<html lang="en">

<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://bootswatch.com/bower_components/bootstrap/dist/css/bootstrap.min.css">
  <link rel="stylesheet" href="https://bootswatch.com/cosmo/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>

<body>
  <div class="navbar navbar-default navbar-fixed-top ">
    <div class="container">
      <div class="navbar-header">
        <a href="#" class="navbar-brand">website</a>
        <button class="navbar-toggle" type="button" data-toggle="collapse" data-target="#navbar-main">
          <span class="icon-bar"></span>
        </button>
      </div>
    </div>
  </div>


  <div style="width:100vw; height: 677px; background-image: url(https://upload.wikimedia.org/wikipedia/commons/8/80/Paul_Gauguin_088.jpg); background-repeat: no-repeat;background-size:cover">
  </div>