6

i want to embed a YouTube video into a website.

This video has a min resolution of 256 × 144 px and a max resolution of 1280 x 720 px.

I want to limit the embedded video to the given resolutions above.

I already found examples for dynamic YouTube embeds but some of them only have a min-width and if i increase the browser size beyond 1280 px width the video keeps expanding with it.

I tried to add a max-width parameter but when i resize the browser the height doesn't resize after this and the video gets chopped at the top and the bottom. which looks like a aspect ratio of 64:9 instead of 16:9.

Also some examples crop my video to a 4:3 aspect ratio, which looks terrible.

Here are the examples i found

CSS:

.video-container {
    position:relative;
    padding-bottom:56.25%;
    padding-top:30px;
    height:0;
    overflow:hidden;
}

.video-container embed {
    position:absolute;
    top:0;
    left:0;
    width:100%;
    height:100%;
}

HTML

<div class="video-container">
  <embed src="youtube code"></embed>
</div>
Lenak
  • 61
  • 1
  • 1
  • 4

1 Answers1

15

I know this is a bit late, but an easy way to achieve that would be to add a <div> around the video container and give that a max-width. It's extra markup, but it works.

Here's a demo (uses SCSS, but same idea): https://codepen.io/mikejandreau/pen/mLbaQQ

Add a wrapper <div> like so:

<div class="video-wrap">
  <div class="video-container">
    <iframe src="https://youtube.com/your-video?rel=0"></iframe>
  </div>
</div>

You can use the CSS you already have with a couple of minor additions. I generally use an <iframe> when embedding videos, but the CSS below has a line for <embed> as well. By adding padding-bottom: 56.25%; to the .video-container, you can keep the height proportional to the width, which in this case translates to a 16:9 aspect ratio.

/* Set your aspect ratio */
.video-container {
  position: relative;
  overflow: hidden;
  height: 0;
  padding-bottom: 56.25%; /* creates a 16:9 aspect ratio */
}

.video-container iframe,
.video-container embed {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  max-width: 100%;
}

/* And set the max-width of the parent element */
.video-wrap {
  width: 100%;
  max-width: 600px;
}

Hope this helps!

Mike Jandreau
  • 392
  • 3
  • 16
  • 2
    This answer should be accepted, works well, easy to understand. Note padding-bottom is used to maintain height to width ratio as padding in percentages is based on width. In the answer "height" is 56.25% of the div's width. – OctaviaLo Dec 01 '20 at 14:27
  • The padding to maintain aspect ratio is so creative. Thank you! – Greg Jackman Jun 19 '22 at 08:10