Full width Youtube embed with React.js — Responsive embed

Kevin Simper
1 min readJan 13, 2019

--

Youtube embed which is not responsive :(

In this article, you will learn how to make a react component that you can use to make a responsive youtube embed react component.

Once you embed your first youtube video, you quickly realize that it is not responsive and that it breaks your design.

Sadly iframes can’t keep it ratio by itself as the domain is a third party, you are not allowed to know the content of the iframe for security and privacy reasons.

So what can you do?

We can make a div that wraps the embed and that scales by default to the window or parent and keeps a scale. That can be archived by using margin and have the iframe within, scale to 100% in both width and height and then limit the height to “56.25%” which is 16/9 in scale.

export default ({ youtubeId }) => {
return (
<div
className="video"
style={{
position: "relative",
paddingBottom: "56.25%" /* 16:9 */,
paddingTop: 25,
height: 0
}}
>
<iframe
style={{
position: "absolute",
top: 0,
left: 0,
width: "100%",
height: "100%"
}}
src={`https://www.youtube.com/embed/${youtubeId}`}
frameBorder="0"
/>
</div>
);
};

Happy responsive coding ;)

--

--

Kevin Simper
Kevin Simper

Written by Kevin Simper

I really like building stuff with React.js and Docker and also Meetups ❤

Responses (4)