那些开源程序中让人叹为观止的代码 - 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

示例程序

posted @ 2014-04-10 14:43  令狐葱★  阅读(1448)  评论(0编辑  收藏  举报