那些开源程序中让人叹为观止的代码 - 3 保持元素纵横比
本專欄嘗試記錄并分享一些個人在學習和使用開源程序代碼的過程中,經意或者不經意間看到的個人感覺比較有參考價值的代碼片段。個人感覺,并不是說能寫或者能看得懂一些晦澀難懂的代碼段子,就可以成為向別人炫耀的資本。本專欄無意炫技,其實也無技可炫。至于讓某些牛人覺得有些小兒科,我只能說,“您老太認真了”。
保持元素縱橫比
解決問題:頁面尺寸變化(resize)時保持頁面元素縱橫比
開源程序:Bootstrap
經常,我們會遇到這樣的需求,需要保持頁面上某些元素在頁面大小被改變重新渲染的時候,保持該元素區域的縱橫比不變。最常見的場景,比如頁面上顯示圖片的時候,希望始終保持圖片的縱橫比,哪怕圖片以縮略圖顯示。或者,在頁面上嵌入一段視頻的時候,希望嵌入的這個元素區域始終保持16:9或者4:3的比例。
在Twitter的開源前端框架中,專門針對后邊一個場景做了處理。
先看頁面使用代碼:
<!-- 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代碼:
.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%就可以了。
這應該算是一個CSS Hack了。有很多人對其做過一些研究和討論,一并列出供參考:
http://www.quora.com/Web-Development/What-are-the-most-interesting-HTML-JS-DOM-CSS-hacks-that-most-web-developers-dont-know-about
http://stackoverflow.com/questions/1495407/css-a-way-to-maintain-aspect-ratio-when-resizing-a-div
其中提到一個簡單的示例程序,可以更容易看到其欲實現的效果:
http://jsbin.com/eqeseb/2/edit
轉載于:https://www.cnblogs.com/jiji262/p/3656478.html
總結
以上是生活随笔為你收集整理的那些开源程序中让人叹为观止的代码 - 3 保持元素纵横比的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: centos6.4下LVS+keepal
- 下一篇: 【VMCloud云平台】SCVMM配置(