如何保持背景图像的宽高比?

Zor*_*gan 19 css

我试着看看其他答案,但没有帮助.我的背景是动态的,因此图像的大小会发生变化,因此我需要保持纵横比,以便看到整个图像.这是我的CSS:

.image_submit_div {
    border: 1px solid #ccc;
    display: inline-block;
    padding: 20px 50px;
    width: 55%;
    height: 320px;
    cursor: pointer;
    background: url('something.jpg'); /* this changes */
    margin: 0 0 25px;
Run Code Online (Sandbox Code Playgroud)

}

HTML

<label for="id_image" class="image_submit_div">
Run Code Online (Sandbox Code Playgroud)

目前,根据图像,有时很多都会被切断.我希望图像缩小,以便可以完全看到.任何的想法?

Jac*_*ray 30

使用background-size: cover;覆盖整个元件,同时保持纵横比

.background-1,
.background-2,
.background-3 {
  /* Set the background image, size, and position. */
  background-image: url('//via.placeholder.com/350x150');
  background-size: cover;
  background-position: center;

  /* Or, use the background shortcut. */
  background: url('//via.placeholder.com/350x150') center/cover;

  margin: 20px;
  border: 1px solid rgba(0, 0, 0, 0.3);
}

.background-1 {
  width: 300px;
  height: 200px;
}

.background-2 {
  width: 200px;
  height: 50px;
}

.background-3 {
  width: 100px;
  height: 200px;
}
Run Code Online (Sandbox Code Playgroud)
<div class="background-1"></div>
<div class="background-2"></div>
<div class="background-3"></div>
Run Code Online (Sandbox Code Playgroud)

如果要在保持纵横比的同时显示整个图像,请background-size: contain;改用:

.background-1,
.background-2,
.background-3 {
  /* Set the background image, size, position, repeat, and color. */
  background-image: url('//via.placeholder.com/350x150');
  background-size: contain;
  background-position: center;
  background-repeat: no-repeat;
  background-color: #fbfbfb;

  /* Or, use the background shortcut. */
  background: #fbfbfb url('//via.placeholder.com/350x150') no-repeat center/contain;

  margin: 20px;
  border: 1px solid rgba(0, 0, 0, 0.3);
}

.background-1 {
  width: 300px;
  height: 200px;
}

.background-2 {
  width: 200px;
  height: 50px;
}

.background-3 {
  width: 100px;
  height: 200px;
}
Run Code Online (Sandbox Code Playgroud)
<div class="background-1"></div>
<div class="background-2"></div>
<div class="background-3"></div>
Run Code Online (Sandbox Code Playgroud)


ab2*_*007 10

使用background-size:contain;,如果你想看到整个图像,并将其延伸到整个宽度或高度(取决于图像的长宽比)的div.

但是如果你想用背景图像覆盖整个div并且不介意图像被裁剪,那么请使用background-size:cover;.

.image_submit_div {
    border: 1px solid #ccc;
    display: inline-block;
    padding: 20px 50px;
    width: 55%;
    height: 320px;
    cursor: pointer;
    background: url('http://www.chinabuddhismencyclopedia.com/en/images/thumb/b/b8/Nature.jpg/240px-Nature.jpg'); /* this changes */
    margin: 0 0 25px;
  background-repeat:no-repeat;
  background-position:center;
  background-size:contain;
}
Run Code Online (Sandbox Code Playgroud)
<label for="id_image" class="image_submit_div">
Run Code Online (Sandbox Code Playgroud)