CSS - 100% width of Youtube embed video

时间:2018-09-18 20:01:04

标签: html css youtube youtube-iframe-api

HTML:

<div class="video">
  <iframe src="https://www.youtube.com/embed/bRhZUF47p2E?version=3&amp;rel=0&amp;controls=0&amp;showinfo=0&amp;autoplay=1&amp;mute=1&amp;loop=1" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
</div>

CSS:

.video {
  width: 100%;
  height: 200px;
  border: 1px solid red;
  overflow: hidden;
  position: relative;
}
iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

JSFIDDLE: http://jsfiddle.net/pj2utq4v/

QUESTION: How to force iframe to be 100% of parent div width. Since parent div is only 200px in height, iframe video would be cropped which is also okay with me.

3 个答案:

答案 0 :(得分:0)

Is there a reason you want to use iframes? I would try using HTML5 video tag. Here's an example: https://www.w3schools.com/html/html5_video.asp then set your video width to 100% like this:

<video width="100%" controls>
  <source src="mov_bbb.mp4" type="video/mp4">
  <source src="mov_bbb.ogg" type="video/ogg">
  Your browser does not support HTML5 video.
</video>

答案 1 :(得分:0)

You can do this changing your CSS classes a little bit:

.video {
    position: relative;
    width: 100%;
    height: 0;
    padding-bottom: 56.25%;
}

iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

JSFIDDLE: http://jsfiddle.net/pj2utq4v/1

答案 2 :(得分:0)

又添加了一个div,其中隐藏了溢出且高度固定,并且可以正常工作。

<div style="height: 200px; overflow: hidden">
  <div class="video">
    <iframe src="https://www.youtube.com/embed/bRhZUF47p2E?version=3&amp;rel=0&amp;controls=0&amp;showinfo=0&amp;autoplay=1&amp;mute=1&amp;loop=1" frameborder="0" allow="autoplay; encrypted-media" allowfullscreen></iframe>
  </div>
</div>
<style>
.video {
  width: 100%;
  height: 200px;
  border: 1px solid red;
  overflow: hidden;
  position: relative;
}
iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
</style>

http://jsfiddle.net/pj2utq4v/