How to center an Youtube iframe horizontally?

How to center an iframe horizontally?

To center a YouTube <iframe> horizontally, you can use CSS. To make you frame center you need to give your videowrapper a specific width and make the margin left and right as auto . Despite you wanna make your frame responsive always use max-width: 100% to your videowrapper Here's how you can do it using different approaches:

How to center an Youtube iframe horizontally?


1. Using text-align on a Parent Container

Wrap the <iframe> in a parent container and apply text-align: center to the container.

html
<div style="text-align: center;"> <iframe width="560" height="315" src="https://www.youtube.com/embed/dQw4w9WgXcQ" title="YouTube video player" frameborder="0" allowfullscreen> </iframe> </div>

2. Using Flexbox

Flexbox is a modern and robust way to center elements.

html
<div style="display: flex; justify-content: center;"> <iframe width="560" height="315" src="https://www.youtube.com/embed/dQw4w9WgXcQ" title="YouTube video player" frameborder="0" allowfullscreen> </iframe> </div>

3. Using margin: auto

This method works when the <iframe> is treated as a block element. You can also explicitly set the display to block.

html
<iframe width="560" height="315" src="https://www.youtube.com/embed/dQw4w9WgXcQ" title="YouTube video player" frameborder="0" allowfullscreen style="display: block; margin: 0 auto;"> </iframe>

4. Using Grid Layout

CSS Grid can also center elements effectively.

html
<div style="display: grid; place-items: center;"> <iframe width="560" height="315" src="https://www.youtube.com/embed/dQw4w9WgXcQ" title="YouTube video player" frameborder="0" allowfullscreen> </iframe> </div>

Which Method to Choose?

  • For simple layouts: Use the text-align: center or margin: auto method.
  • For modern and responsive layouts: Use flexbox or grid.

These approaches ensure that your YouTube iframe will stay horizontally centered across various screen sizes.

Let's have an example

<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
.container {
  position: relative;
  width: 50%;
  overflow: hidden;
  padding-top:30%; /* 1:1 Aspect Ratio */
}
.responsive-iframe {
  position: absolute;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  width: 100%;
  height: 100%;
  border: none;
}
</style>
</head>
<body>
<h2>Responsive Iframe</h2>
<h3>Maintain Aspect Ratio 1:1</h3>
<p>Resize the window to see the effect.</p>
<div class="container" align="center"
  <iframe class="responsive-iframe" src="https://www.youtube.com/embed/tgbNymZ7vqY"></iframe>
</div>
</body>
</html>

Conclusions:-

Within the code for that iFrame, type “align=center”. This will tell your page to center the iFrame. You can also center the image by editing its height and width on the page.

Comments