小编典典

如何保持背景图片的长宽比?

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;

}

html

<label for="id_image" class="image_submit_div">

此刻取决于图像,有时很多图像被切除。我希望缩小图像以便可以完全看到。任何的想法?


阅读 603

收藏
2020-05-16

共1个答案

小编典典

使用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;

}


<div class="background-1"></div>

<div class="background-2"></div>

<div class="background-3"></div>

如果要显示整个图像,同时保持宽高比,请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;

}


<div class="background-1"></div>

<div class="background-2"></div>

<div class="background-3"></div>
2020-05-16