/ walking bear:D / Shrink a YouTube video to responsive width

Shrink a YouTube video to responsive width

2017-05-07 posted in [筆記]

在這個網站整合 youtube embedded frame,碰到一些 CSS 的調校問題,這篇問答:Shrink a YouTube video to responsive width 提供了一些 CSS 相關的技術背景知識。先看最後的 CSS code

.videoWrapper {
  position: relative;
  padding-bottom: 56.25%; /* 16:9 */
  padding-top: 25px;
  height: 0;
}
.videoWrapper iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

最大的問題點在於保持正確的長寬比 aspect ratio,要達成預期的效果,得在 youtube iframe 外再包覆一層神奇的 <div class="videoWrapper>...</div>div height 設為 0,但又設定了 padding-bottom: 56.28%padding bottom 是參考該 div 的寬度 (自動撐開至 parent 的寬度,填好填滿),神奇的數字 56.28% = 16 / 9。 另一個奧妙的關鍵在於 iframe position: abosoluteiframe 會咬住外面那層 div 內的絕對位置,width: 100% 也是一個填好填滿的概念,有趣的是 height: 100% 會漫開到 div padding-bottom 區域,如此一來就剛剛好維持住 youtube 的長寬比。 這篇文章:Creating Intrinsic Ratios for Video 雖然有點過時,概念介紹卻很清晰。還給了一個入門用例,做出一個隨著視窗大小調整,卻維持固定 1:5 高寬比的區域。

.wrapper-with-intrinsic-ratio {
	position: relative;
	padding-bottom: 20%;
	height: 0;
}

.element-to-stretch {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background: teal;	
}

CSS 有太多神奇密技,而且必須考慮一堆 browser 兼容問題,站在技術的角度,應該多加利用 twitter-bootstrap

. reply_count: 0 get_replies : 0 .

walking bear:DRSS feed

关于

wkliang

Clarke's Three Laws:

  • When a distinguished but elderly scientist states that something is possible, he is almost certainly right. When he states that something is impossible, he is very probably wrong.
  • The only way of discovering the limits of the possible is to venture a little way past them into the impossible.
  • Any sufficiently advanced technology is indistinguishable from magic.
  • 版权申明

    知识共享许可协议

    Fork me on GitHub

    Powered by

    Disqus, GitHub, Google Custom Search, Gravatar, HighlightJS, jekyll