具有保留宽高比的响应式iframe

时间:2017-07-31 07:53:42

标签: javascript html css iframe youtube

我是编码和社区的新手,我正在尝试相应地嵌入YouTube iframe。到目前为止,我所做的只是将原始宽度值替换为100%。

 <iframe width="100%" height="315" src="https://www.youtube.com/embed/kXBunIe_PSw" frameborder="0" allowfullscreen></iframe>

是的它使它具有响应性,因为高度是静态的,有很多黑色空间。有没有简单的方法来防止这种情况。

我更喜欢css解决方案,但也欢迎javascript。

2 个答案:

答案 0 :(得分:0)

&#13;
&#13;
.videoWrapper {
	position:relative;
	padding-bottom:56.25%;
	margin:auto;
	height:0;
}
.videoWrapper iframe {
	background-color:#f2f2f2;
	position:absolute;
	max-width:100%;
	max-height:315px;
	width:95%;
	height:95%;
	left:0;
	right:0;
	margin:auto;
}
&#13;
    <div class='videoWrapper'>
      <iframe id='video' class='trailervideo' width='560' height='315' src='https://www.youtube.com/embed/hhR3DwzV2eA' src='about:blank' frameborder='0' allowfullscreen></iframe>
    </div>
&#13;
&#13;
&#13;

请告诉我,如果它不起作用

答案 1 :(得分:0)

这应该可以帮助您入门。

参考:Bootstrap

.responsive {
  position: relative;
  display: block;
  height: 0;
  padding: 0;
  overflow: hidden;
}

.responsive iframe {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  height: 100%;
  width: 100%;
  border: 0;
}

.video {
  padding-bottom: 56.25%;  /* or 75% depending upon the type of video you have */
}
<div class="responsive video">

  <iframe src="https://www.youtube.com/embed/kXBunIe_PSw" allowfullscreen></iframe>

</div>