Responsive videos

Beginner CSS tutorial: In this tutorial, you will learn how to embed YouTube videos and make them responsive (using just CSS).

Demo

Responsive videos

  1. Get your embed code from YouTube which is found underneath the video of your choice.youtubeTutorial01
  2. You will need to wrap the iframe code in a DIV then give it a class name of your choice.
    <div class="videoWrapper">
    <iframe width="560" height="315" src="//www.youtube.com/embed/2vjPBrBU-TM" frameborder="0" allowfullscreen></iframe>
    </div>
    
  3. Add the following CSS code to your stylesheet. I have included iframe, object and embed for other video players.TIP: The bottom padding of 56% is for the aspect ratio of 16:9 videos. Use 75% for a 4:3 video and 42% for a 24:10 video. You may need to experiment with altering this number if you would like a video player with a different size.
    .videoWrapper {
    	position: relative;
    	padding-bottom: 56%; /* 16:9 */
    	height: 0;
            overflow: hidden;
    }
    .videoWrapper iframe,  
    .videoWrapper object,  
    .videoWrapper embed {
    	position: absolute;
    	top: 0;
    	left: 0;
    	width: 100%;
    	height: 100%;
    }
    
  4. With the above CSS, the YouTube iframe’s width will always 100% of the parent element e.g. your web template’s container/wrapper. Use this CSS if you’d like a fixed size and change the width value to your choice.
    .fixedwidth {
    	width: 100%;
    	max-width: 560px;
    }
    

Don’t forget to check out the live demo of this tutorial. Try resizing the browser window or check it out on screenfly to see what the video player looks like in other resolutions.

Share
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Leave a Reply

Your email address will not be published. Required fields are marked *