Youtube视频100%宽度和自定义高度

时间:2016-09-13 08:24:48

标签: html css iframe youtube

我在我的网站上想要添加宽度为100%且高度为400px的视频;我尝试了以下方法:

.container {
  position: relative;
  width: 100%;
  height: 0;
  padding-bottom: 56.25%;
}
.video {
  position: absolute;
  top: 0;
  left: 0;
  width: 100% !important;
  height: 400px;
}
<div class="container">
  <iframe class="video" src="//www.youtube.com/embed/yCOY82UdFrw" width="300" height="150" frameborder="0" allowfullscreen="allowfullscreen">
  </iframe>
</div>

但我的视频结果如下: click me pls

内部不是100%。

有没有人知道如何解决这个问题?我很感激。

谢谢,

凯文

4 个答案:

答案 0 :(得分:3)

请记住,百分比宽度或高度必须具有显式声明某种维度的父元素。在这种情况下,它是:

html, body {width:100%; height:100%;}

对于身高,你仍然可以保持灵活性并拥有400px:

height: auto;
min-height: 400px;

&#13;
&#13;
html,
body {
  height: 100%;
  width: 100%;
}
.container {
  position: relative;
  width: 100%;
  height: 0;
  padding-bottom: 56.25%;
}
.video {
  position: absolute;
  top: 0;
  left: 0;
  width: 100% !important;
  height: auto;
  min-height: 400px;
  overflow: hidden;
}
&#13;
<div class="container">
  <iframe class="video" src="//www.youtube.com/embed/yCOY82UdFrw" frameborder="0" allowfullscreen="allowfullscreen">
  </iframe>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

// By Chris Coyier & tweaked by Mathias Bynens

$(function() {

	// Find all YouTube videos
	var $allVideos = $("iframe[src^='http://www.youtube.com']"),

	    // The element that is fluid width
	    $fluidEl = $("body");

	// Figure out and save aspect ratio for each video
	$allVideos.each(function() {

		$(this)
			.data('aspectRatio', this.height / this.width)
			
			// and remove the hard coded width/height
			.removeAttr('height')
			.removeAttr('width');

	});

	// When the window is resized
	// (You'll probably want to debounce this)
	$(window).resize(function() {

		var newWidth = $fluidEl.width();
		
		// Resize all videos according to their own aspect ratio
		$allVideos.each(function() {

			var $el = $(this);
			$el
				.width(newWidth)
				.height(newWidth * $el.data('aspectRatio'));

		});

	// Kick off one resize to fix all videos on page load
	}).resize();

});
<iframe width="1280" height="750" src="//www.youtube.com/embed/yCOY82UdFrw?rel=0&amp;hd=1" frameborder="0" allowfullscreen></iframe>

答案 2 :(得分:0)

只需替换此行代码

<iframe class="video" src="//www.youtube.com/embed/yCOY82UdFrw" width="300" height="150" frameborder="0" allowfullscreen="allowfullscreen">
</iframe>

用这个:

<iframe class="video" src="//www.youtube.com/embed/yCOY82UdFrw" width="1200" height="720" frameborder="0" allowfullscreen="allowfullscreen">
</iframe>

让我知道会发生什么?

答案 3 :(得分:0)

只需添加iframe的width和height属性即可。请看样品:

<iframe src="https://www.youtube.com/embed/yourVideo" width="100%" height="500px"></iframe>