2015-02-24 101 views
0

我想在瀏覽器調整大小時保持div的縱橫比。調整大小時保持div寬高比

我以前有過這個問題,然後解決方法是使用padding-bottom以百分比。

e.q.如果我想要一個類foo div有長寬比2:1我會有一些CSS看起來像這樣。

.foo{ 
    width: 100%; 
    padding-bottom: 50%; 
} 

在這種情況下(2/1)*100 = 50%數學(height/width)*100 = percentage。如果你想要一個長寬比爲16:9的div,數學是(9/16)*100 = 56.25%

這對我以前的工作,但現在它沒有。 我有以下fiddle,所以你可以看到我的意思。

看來.caption-wrap有一個高度,但我不知道它來自哪裏。

+0

的額外高度belons到的內容的高度。即內容應該絕對定位,以免影響計算出的高度。 – 2015-02-24 09:11:55

+0

@HashemQolami像[this](http://jsfiddle.net/hpmu8wh0/2/)? – 2015-02-24 09:13:48

+0

您是否嘗試使用height:0作爲.caption-wrap? – kuba 2015-02-24 09:14:44

回答

0

檢查這個例子:

/* 
* Pure CSS aspect ratio with no spacer images or js! :) 
*/ 

body { 
    width: 36%; 
    margin: 8px auto; 
} 

div.stretchy-wrapper { 
    width: 100%; 
    padding-bottom: 56.25%; /* 16:9 */ 
    position: relative; 

    background: blue; 
} 

div.stretchy-wrapper > div { 
    position: absolute; 
    top: 0; bottom: 0; left: 0; right: 0; 

    color: white; 
    font-size: 24px; 
    text-align: center; 
} 

/* Other aspect ratios to try: 
* 56.25% = 16:9 
* 75% = 4:3 
* 66.66% = 3:2 
* 62.5% = 8:5 
*/ 

鏈接dabblet:http://dabblet.com/gist/2590942

相關問題