DIY: How to embed YouTube videos

Do you manage a website or a blog, and include YouTube videos in your posts or articles? If yes, have you ever wondered about better ways to embed them?

Because, in the end, a better way always exists. Read on for more!

YouTube logo

You may want to rotate your phone in order to improve your browsing experience on this site.

Quick links

For starters

The obvious way to embed a YouTube video would be using its Share button while it plays on YouTube, then clicking on Embed.

YouTube embed widgetGet code to embed a video playing on YouTube
Notice how player size is already selected for you

This will provide you with a piece of HTML, which, placed on your webpage, will display a player ready to stream the video in question.

Configuration options available here are minimal, though. You can choose to dispose of player controls (rarely helpful), select a time into the clip when to start the playback (can make sense), and enable the privacy-enhanced mode.

The latter is well worth activating. In doing so, you will change the streaming server, prevent annoying ads from landing in your visitor's browser, and save her a load of tracking and other cookies she has no idea of.

Aside from that, you won't be able to choose the player size for your page. Even its aspect ratio will be set to default, widescreen 16×9, regardless of the actual format at hand.

Still, you can copy the offered code and paste it elsewhere to use as is.

Before you do, take a second to turn that privacy-enhanced mode on. You owe your visitors that much, trust me.

For everything else, keep reading!

For friends of right proportions

The first step in adjusting the player to your website design would be fitting it with adequate dimensions.

These need to be expressed in absolute pixel values, and featured in width and height attributes of the iframe to host the player.

A dedicated section further down explains how to set up a responsive player which would shrink or grow with its container.

As of now, most YouTube videos sport one of two aspect ratios, the longer / wider 16×9 and the squarer / higher 4×3.

The actual video clip format doesn't matter at all — you will find [more than] enough examples presented in a wrong way. At best, these videos appear surrounded by black stripes. In many cases, though, they stretch and deform to meet the incorrect ratio.

For the best possible user experience with embedded videos on your pages follow some simple recommendations:

  • Find a YouTube video presenting the clip in the correct aspect ratio — and featuring the latter itself. As a rule of thumb, the fewer black borders are visible in the player on YouTube, the better.
  • The player iframe will take up the entire area specified by its attributes. If their proportion does not match the exact aspect ratio of the video within, the extra space will show in black. You may find it useful in some cases, but, in general, I would rather advise against it and favour "borderless" embeds instead, namely:
  • If your page template provides only limited space for the video container, go for the width. For example, this column is 520px wide, fixed. When I embed videos here, frames to host them are sized at 520px wide and either 390px or 292px high, for clips in the 4×3 format and in widescreen, respectively.
  • If your design offers enough real estate, strive for the best video quality. Use the available video resolution, say, 480px, for the frame height, and calculate the width accordingly, i.e., 640px (= 480 × 4 ÷ 3) or 853px (= 480 × 16 ÷ 9).

Compare examples below, all featuring the same — or almost — video clip in different presentations:

YouTube video is in the wrong aspect ratio – the clip is stretched sideways YouTube video and player are in 16×9, the clip playing is in – correct – 4×3 Correct and matching – I would consider this the best version to embed as is

For creative enhancers

Did you know you could modify embedded YouTube videos in different ways on the fly, where you insert them? Look at the examples to see what I mean.

Again, let's talk about video formats and aspect ratios, and try to correct them this time.

Take the first video above. The problem here is, its 16×9 aspect ratio is too wide for the clip in the 4×3 format. To correct its appearance, we'd need to make it 75% its current width.

Here is the math: (4/3) ÷ (16/9) = .75.

Modern HTML5 browsers are capable of doing this with any kind of content whose style includes a scaling transform rule.

We need to declare the iframe with our desired height, 390px for a 4×3 video on this page, and its respective width in the original video format, 390 × (16 ÷ 9) = 693.

Then we can tell the browser to scale iframe width down to 75%, et voilà:

Correct the aspect ratio with transform:scale

Of course, everything else within the player – controls, texts, images, etc., – will shrink as well, but I think this is a small price to pay compared to the fully restored visuals!

The same goes for the toned video. It is possible to recover it with another style option, filter. Here you can choose between two functions to remove the tint, namely convert to grayscale at 100%, or (de-)saturate by 0.

Use style filter functions to change look and feel, here grayscale

Everything inside the iframe will now appear in black and white, but I am OK with it.

Styling with filter also provides a function for sepia toning. You can utilise it with your video embeds to achieve the very effect we've just offset.

The last example shows how to crop YouTube videos when embedding them.

The idea is similar to pan&scan, the technique used to translate widescreen cinema output into something more suitable for home TV sets, when those were still the standard 4×3 affair.

For this, the player iframe is placed inside another container, then enlarged and positioned in such a way within the latter that only some part of it stays visible. This is achieved by styling the container to be smaller, and to hide overflow.

In the example, the widescreen video is sized to make the clip playing inside it full width of this column. The black border ends up outside container limits, and is removed by the overflow rule.

Unfortunately, player controls are also pushed out of sight. You will have to click or tap on the video in order to pause or resume its playback.

Containers can help crop embedded videos, here at cost of player controls

Now if you were to embed these videos, you would possibly have a harder time to decide on one!

In the end, something important to keep in mind. Be sensitive to modifying copyrighted material!

For deep divers

As hinted in the beginning, there are many more configuration options for video embeds than offered on YouTube.

Below is the complete parameter list to use with an embedded player. To apply any of them, append a question mark to the iframe source URL and add the corresponding name=value pairs. Separate multiple parameters by the & character.

This is an interactive feature. Tick off any parameters to set their respective non-standard values, then click the button under the table to generate the iframe code.

You will have to change all required placeholders, designated by CAPITALS, to their correct values. Do it before or after copying the code, and simply paste it on your page where you want the video(s) to appear.

Parameter

Possible values
Default values in bold

1 – Start playing video automatically when the player loads.
0 – Do not play video automatically when the player loads.

The parameter, two-letter language code, specifies the default language the player will attempt to use for captions.

1 – Override user setting for closed captions, and show them by default.

Set the colour of the player progress bar to:
red
– white [this will also disable the modestbranding setting]

1 – Display player controls in the video player.
0 – Do not display player controls in the player.

1 – Disable keyboard controls in the player.
0 – Enable player keyboard controls. These include:

  • Spacebar or [k]: Pause / play the video.
  • Left arrow: Jump back 5 seconds in the video.
  • Right arrow: Jump ahead 5 seconds in the video.
  • Up arrow: Volume up.
  • Down arrow: Volume down.
  • [f]: Toggle full-screen mode.
  • [j]: Jump back 10 seconds in the video.
  • [l]: Jump ahead 10 seconds in the video.
  • [m]: Toggle mute playback.
  • [0-9]: Jump to a point in the video, in 10%-steps from the beginning.

1 – Enable JavaScript IFrame Player API.
0 – Do not enable the Player API.

Stop the video after the specified number of seconds.

1 – Display a button to show the video in fullscreen.
0 – Hide the button to show the video in fullscreen.

Fullscreen mode makes sense for high-definition videos only. Clips in SD quality, 480px and under, won't look any good in fullscreen — it is advisable to remove the button (and allowfullscreen iframe attribute) for them from the player.

If set, enforces the specified locale (e.g., en or en-us) to be used within the player for tooltips and other services, instead of the browser locale.

1 – Show video annotations.
3 – Do not show video annotations (recommended).

Both parameters have to be used together.

listType

 

list

 

YouTube playlist ID, prepended with PL.

 

Search query term used to select content to play.

 

YouTube channel to select videos from.

1 – Play the single loaded video again and again. Or, repeat the loaded playlist after it has played to the end.
0 – Stop after the video or the playlist has finished.

1 – Remove the YouTube logo from the control bar.
0 – Display the YouTube logo in the control bar.

For API enabled players only. Limits the IFrame Player API functionality to the specified domain only, and prevents its execution when used on another location.

A comma-separated list of video IDs to be played in sequence after the video specified in the iframe src has finished.

The parameter controls how videos should play in an HTML5 player on iOS.
1 – Play UIWebViews created with the property allowsInlineMediaPlayback set to true.
0 – Play videos in fullscreen.

Specifies how related videos shown after the playback are chosen.
1 – Default YouTube selection.
0 – Related videos will come from the same channel as the video just played.

Value in seconds into the video to start the playback from.

Defines the URL to count as the traffic source for the video in YouTube Analytics instead of the browser location.

For fans of sensitivity

As you saw above, embedding a YouTube video in an iframe player requires specifying the latter's exact dimensions in absolute units, that is, pixels. How can you make it responsive, adjusting automatically to any screen size and appearing consistent on any device?

The idea is, again, to use containers styled in a way that will fit them into available space.

  • Start with defining the maximal size you would like the video to appear in. This will usually follow the available video quality and/or your site design template. For example, with a widescreen video playable at 480px, and a one-column responsive page, you may opt for the full-scale 853×480px presentation.

  • Based on this, decide on the final player proportions, for example, to include some extra free space above and below (to appear in black). Let's settle on "pure" 853×480px this time.

  • Place an outer container whose both width and max-width are set by style rules. Use width equal to the highest video width, and max-width at 100% (of its parent's width). In this way, the video will either run at full width as you defined it, or at full width of your site visitor's browser, whatever is smaller.

  • Position another div container in the first one. This will take care of keeping the video height consistent with its aspect ratio when the width changes.

  • For this, specify a bottom padding in percent – and that's the trick – of its width. A widescreen video like ours will require padding of (9÷16) × 100% = 56.25%. For a 4×3 video you'll need to value it at (3÷4) × 100% = 75%. Since the height isn't set explicitly, this padding will completely take it up.

  • Define the inner container div as position anchor for its children with position=relative.

  • Now size the player iframe at 100% for both width and height, and place it in the top left corner of the inner container.

  • Enjoy the show!

The example below is fully functional. I styled the page to become responsive for the most part. You are welcome to resize your browser window while the video is playing. (Be prepared for content jerking around, and ready to scroll for catching up with it.) Or, load the page on your mobile phone.

Responsive player setup with two containers

For lone wolves

If you would like to have full control over the visual presentation and overall behaviour of YouTube videos on your online property, consider embedding them with the IFrame Player API enabled.

The API offers several low-level JavaScript functions which allow to operate the player from outside. With them you will be able to provide custom player controls and your own video covers, for example.

It will be also possible to tweak other, more essential things. How would you like individual start and end points for videos in a playlist, own intertitles and animated sequences to show up during the playback, or any other nifty ideas you can imagine?

Anything is quite possible.

In a rough outline, the player instance exposed by the API will trigger events every time its status changes. Your script would listen and respond to these events for purposes of your application.

Likewise, events initiated by your proprietary controls can be used as cues to manipulate the player by calling API functions.

For details you will have to delve into the documentation available on Google Developers'. Don't miss the video presented on the page and featuring code samples!

Make sure to peruse the English version if you connect with a browser running in another language.

The small example below is just a quick peek at what is on offer. The video is a lengthy live performance with four acts and some talk between them. The custom controls allow you to play/pause the video and jump to songs' starting points. The progress bar is not interactive, nor is the whole setup responsive, but you should get the idea.

 
 
 
00:00 / 00:00
Look, ma, new buttons!

For fast movers

One last thing…

It is no secret that videos are rather heavy resources to deal with online. The very placing of a YouTube player on your page can put substantial strain on the load time. This is especially true for mobile users and slow connections.

How can you help your site visitors avoid long waiting times, and still provide rich content for those interested in it?

Try lazy loading resources of significant size.

The idea is to use a lightweight placeholder object, say, a 1x1px transparent image, and postpone downloading real content until someone actually scrolls to its position on page.

The small JavaScript library referenced in the Links section below is very easy to install and use. All video examples on this page are powered by it — scroll around to see it in action.

Tags: #websearch #youtube #video #diy

In this series

Custom site search with DuckDuckGo
Build your own custom search widget for your website or blog! Use the easy to follow steps to generate its code, and test it on the fly — within minutes.
YouTube Player API reference
The API is actually an old hat, developed around 2011 or so. This is the reference in English, the only one that seems being kept up to date.
Yet Another Lazy Loader
A great small JavaScript utility for lazy loading of YouTube videos and other heavy content. The minified version to include on your pages takes up just over 3 kb.
KEXP YouTube channel
"…a nonprofit arts organization serving music lovers and artists through in-person, broadcast, and online programming. KEXP operates one of the most influential listener-supported music radio stations in the world." Their Icelandic Bands playlist nears 900 titles. You are in for serious listening.
Stromae: Live in Montreal
An impressive live concert from the performers in the last two videos on the page. Nearly two hours long, full HD, subtitled in English. To whom it may concern: Beware strobe light effects throughout.

Unattributed images on this page are sourced from Pixabay.
Featured videos appear on following YouTube channels: BlackVEVO, Dulgar, Dvj Luiz Phanton, KEXP, Stromae.

How to embed YouTube videos

Back to Top

Tell me what you think!

Is it useful 👍? Awful 👎? Leave a message! Your comments help make this site better (and give me a kick—one way or another).

Popular articles

  1. A kind of magic

    If a digital picture has to be seen in the real world, printed on a real medium and displayed in a real showcase, its transition from RAW to real is better done in an old school image editor. Enter A…

    Read on

  2. A duck for a dog

    If you got your own place on the Internet, helping your visitors find what they are looking for is a great way to engage them and keep them staying a bit longer. A custom site search can achieve just …

    Read on

  3. "Might as well have the best"

    Aiming for better images? Think better lenses! This is your most important piece of gear, so you better get it sorted out. — Need some advice?

    Read on

Back to Top

⦿ Current offer ⦿

  1. 10% off framed large format prints over 260 € until November 17, 2019!

🗞 Subscribe!

Featured content