Go to main content

Textpattern CMS support forum

You are not logged in. Register | Login | Help

#1 2021-07-23 11:36:44

John-Paul F
Member
Registered: 2021-03-15
Posts: 39
Website Twitter

How to centre an iframe (eg, YouTube video)?

I want to centre a YouTube video.

I tried putting p=. at the start of the line.
No good.

Any idea what to put inside the iframe code itself?


Strictly Amateur

Offline

#2 2021-07-23 12:09:15

Bloke
Developer
From: Leeds, UK
Registered: 2006-01-29
Posts: 11,271
Website GitHub

Re: How to centre an iframe (eg, YouTube video)?

This is one of those things that’s trickier to do than it should. I solve it like this:

<div class="videoResponsive">
   <iframe src="https://example.org/embed/url" frameborder="0" allowfullscreen></iframe>
</div>

And then let CSS do the legwork:

img, video {
    width: 100%;
    height: auto;
}
.videoResponsive {
    padding-bottom:56.25%;
    height:0;
    position:relative;
    padding-top:30px;
    overflow:hidden;
}
.videoResponsive iframe, 
.videoResponsive object, 
.videoResponsive embed {
    position:absolute;
    left:0;
    top:0;
    width:100%;
    height:100%;
}

That should make any contained video inside the videoResponsive container scalable on all devices regardless of its aspect ratio. If you then want to centre it on wider viewports, add a media query and limit the width or max-width of the videoResponsive container, then employ the usual margin:0 auto; rule to centre it. Though that might truncate the iframe content left and right so you may have to adjust that too.

Hope that helps until a proper CSS guru can chime in.


The smd plugin menagerie — for when you need one more gribble of power from Textpattern. Bleeding-edge code available on GitHub.

Txp Builders – finely-crafted code, design and Txp

Offline

#3 2021-07-23 12:40:56

Myusername
Member
Registered: 2019-12-12
Posts: 162

Re: How to centre an iframe (eg, YouTube video)?

An alternative to Stef’s solution is to use the aspect-ratio property on your container:

.videoResponsive {
	aspect-ratio: 16/9;
}
.videoResponsive iframe {
	width: 100%;
	height: 100%;
}

Also, if you want to save a few more lines of code at article time, you can do the following:

p(videoResponsive). <iframe src="https://www.youtube.com/embed/Q0oIoR9mLwc" frameborder="0" allowfullscreen></iframe>

Last edited by Myusername (2021-07-23 12:49:16)

Offline

#4 2021-07-23 12:47:09

philwareham
Core designer
From: Haslemere, Surrey, UK
Registered: 2009-06-11
Posts: 3,564
Website GitHub Mastodon

Re: How to centre an iframe (eg, YouTube video)?

Soon you’ll just need something as simple as this CSS to do a centered video iframe:

iframe {
    aspect-ratio: 16/9;
    width: 100%;
    max-width: 720px;
    margin-inline: auto;
}

Alas, we are not quitethere yet.

Offline

Board footer

Powered by FluxBB