防止div拉伸其背景图像

And*_*rew 1 html css background-image

我有一个div,其背景图片在样式表中定义如下:

.information_photo {
  position: relative;
  top: 30px;
  width: 100%;
  height: 200px;
  background-image: url('http://www.ladyblitz.it/wp-content/uploads/2015/04/carbonara.jpg');
  background-repeat: no-repeat;
  background-position: center center;
  background-size: 100% 100%;
}
Run Code Online (Sandbox Code Playgroud)
<div class="information_photo"></div>
Run Code Online (Sandbox Code Playgroud)

如您所见,它拉伸了原始图像,相反,我希望它仅聚焦于背景图像的一部分,而不拉伸或调整其大小。

Geo*_*rge 5

100% 100% background-size值表示背景应拉伸元素宽度的(100%)和元素高度的(100%)。将其中一个设置为auto,这将自动调整未定义尺寸的大小,同时保留图像的宽高比。

然后,您可以通过调整相应的background-position样式来选择可见的图像部分。

.information_photo {
  position: relative;
  top: 30px;
  width: 100%;
  height: 200px;
  background-image: url('http://www.ladyblitz.it/wp-content/uploads/2015/04/carbonara.jpg');
  background-repeat: no-repeat;
  background-position: center -30px; /* Visible 30 px from the top */

  /* 100% height, auto width */
  background-size: auto 100%;

  /* 100% width, auto height */
  background-size: 100% auto;
  /* or simply */
  background-size: 100%;
}
Run Code Online (Sandbox Code Playgroud)
<div class="information_photo"></div>
Run Code Online (Sandbox Code Playgroud)