2017-01-10 83 views
7

我試圖看看其他答案,但沒有幫助。我的背景是動態的,所以圖像的大小會發生變化,所以我需要保持寬高比,以便看到整個圖像。這裏是我的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"> 

在根據圖像上的那一刻,很多有時它被切斷。我希望圖像縮小以便能夠完全看到。任何想法?

+0

我試圖他們所說的(背景尺寸:200像素50像素)或背景尺寸:100%100%);它仍然不起作用 - 仍然切斷大部分圖片 – Zorgan

回答

12

使用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://lorempizza.com/500/500'); 
 
    background-size: cover; 
 
    /* Or use the background shorthand */ 
 
    background: url('http://lorempizza.com/500/500') scroll no-repeat center/cover; 
 
    margin: 0 0 25px; 
 
}
<div class="image_submit_div"></div>

+0

這很好,謝謝!無論大小,它現在顯示完整的圖像。 – Zorgan

+0

@Zorgan很高興我能幫忙:) –

8

使用background-size:contain;如果要看到整個圖像,並將其拉伸到全寬度或高度(取決於圖像的寬高比)。

但是,如果你想覆蓋整個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; 
 
}
<label for="id_image" class="image_submit_div">