防止div拉伸其背景图片

4

我有一个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%;
}
<div class="information_photo"></div>

如您所见,它拉伸了原始图像,而我只想让它专注于背景图像的某一部分,而不会拉伸或调整大小。

1个回答

12

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%;
}
<div class="information_photo"></div>


工作得非常好。非常感谢George,我会尽快接受答案! :) - Andrew

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接