creating websites is a passion
descriptive text

How to create a YouTube / Vimeo video background

The first hurdle is probably the parameters. While Vimeo gives pretty clear hints when embedding, Youtube has a small significant hindrance.



<iframe src="" allow=autoplay></iframe>


<iframe src=""></iframe>

If you use a short video you’ll notice how the related videos show once the video is finished. To avoid this we have to use a little trick. Adding the parameter loop=1 to the source of the video is no longer enough, we have to add more parameter and this is the playlist one to which we will assign the ID of the youtube video.



The iframe will have an absolute position that will allow us to position the iframe exactly where we want it. To apply a negative top margin of half the video’s height, and a negative left margin of half the video’s width. This will offset the iframe relative to the element (not the parent container) centering the YouTube video background vertically and horizontally.

<div class="video-container">
  <iframe id="my-iframe" src=""></iframe>

The calculation is now to keep the aspect ratio.

*, ::before, ::after {
  -webkit-box-sizing: border-box;
  box-sizing: border-box;

  overflow-x: hidden;
  margin: 0;

  position: relative;
  width: 100vw;
  /* height = 100 * (9 / 16) = 56.25 */
  height: 56.25vw;
  overflow: hidden;

 /* absolute centered */
.video-container iframe {
  position: absolute;
  top: 50%;
  left: 50%;
  width: 100vw;
  height: 100%;
  transform: translate(-50%, -50%);
  pointer-events: none;
  border: none;

@media (min-aspect-ratio: 16/9) {
  .video-container iframe {
    /* height = 100 * (9 / 16) = 56.25 */
    height: 56.25vw;

 /* width in relation of the height */
@media (max-aspect-ratio: 16/9) {
  .video-container iframe {
    /* width = 100 / (9 / 16) = 177.777777 */
    width: 177.78vh;

All together

Thanks to

Picture by Matthew Kwong

Back to blog