Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
213 views
in Technique[技术] by (71.8m points)

html - Automatic height when embedding a YouTube video?

i've embed a YouTube video on my website but the trouble is that i need the height to automatically adjust based on the width and the aspect ratio of the video. So if my width is 1280, my height should be 720 if the video is 16:9. I've tried using 'VW' and 'VH' units but these don't seem to work with an iframe. My width is already set proportionally.

My code is below:

<iframe style="margin-right: 1%; margin-left: 1%;" width="98%" height="" src="https://www.youtube.com/embed/HwzQbfde-kE" frameborder="0"></iframe>
question from:https://stackoverflow.com/questions/35814653/automatic-height-when-embedding-a-youtube-video

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can solve it by this code. Live example Link

CSS:

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

Example Html

<div class="video-container">
    <iframe width="560" height="315" src="https://www.youtube.com/embed/_TyJeKKQh-s?controls=0" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe>
</div>

How this works: The container element is given a zero height and a percentage bottom padding. The percentage bottom padding is a percentage of the container width, so that gives it a fixed aspect ratio. But in order to get the iframe to show up inside the zero-height container, you need to make the container relative and the iframe absolute, positioned inside the div.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...