本專欄嘗試記錄並分享一些我的在學習和使用開源程序代碼的過程當中,經意或者不經意間看到的我的感受比較有參考價值的代碼片斷。我的感受,並非說能寫或者能看得懂一些晦澀難懂的代碼段子,就能夠成爲向別人炫耀的資本。本專欄無心炫技,其實也無技可炫。至於讓某些牛人以爲有些小兒科,我只能說,「您老太認真了」。javascript
解決問題:頁面尺寸變化(resize)時保持頁面元素縱橫比css
開源程序:Bootstrap前端
常常,咱們會遇到這樣的需求,須要保持頁面上某些元素在頁面大小被改變從新渲染的時候,保持該元素區域的縱橫比不變。最多見的場景,好比頁面上顯示圖片的時候,但願始終保持圖片的縱橫比,哪怕圖片以縮略圖顯示。或者,在頁面上嵌入一段視頻的時候,但願嵌入的這個元素區域始終保持16:9或者4:3的比例。java
在Twitter的開源前端框架中,專門針對後邊一個場景作了處理。git
先看頁面使用代碼:github
<!-- 16:9 aspect ratio --> <div class="embed-responsive embed-responsive-16by9"> <iframe class="embed-responsive-item" src="…"></iframe> </div> <!-- 4:3 aspect ratio --> <div class="embed-responsive embed-responsive-4by3"> <iframe class="embed-responsive-item" src="…"></iframe> </div>
這裏比較值得一提的就是樣式類embed-responsive-4by3和embed-responsive-16by9的實現。看CSS代碼:web
.embed-responsive .embed-responsive-item, .embed-responsive iframe, .embed-responsive embed, .embed-responsive object { position: absolute; top: 0; bottom: 0; left: 0; width: 100%; height: 100%; border: 0; } .embed-responsive.embed-responsive-16by9 { padding-bottom: 56.25%; } .embed-responsive.embed-responsive-4by3 { padding-bottom: 75%; }
這裏經過巧妙的使用padding-bottom這個屬性,來保持元素的縱橫比。好比embed-responsive-4by3,就是將width設置爲100%,而後將padding-bottom設置爲4:3對應的百分比,也就是75%就能夠了。bootstrap
這應該算是一個CSS Hack了。有不少人對其作過一些研究和討論,一併列出供參考:前端框架
http://stackoverflow.com/questions/1495407/css-a-way-to-maintain-aspect-ratio-when-resizing-a-div
其中提到一個簡單的示例程序,能夠更容易看到其欲實現的效果:
http://jsbin.com/eqeseb/2/edit