如何居中嵌入的YouTube iframe?产品落地页开发问题求助
Hey there! Let's get that YouTube iframe centered properly—your current margin: auto isn't working because iframes are inline-block elements by default, and margin: auto only centers block-level elements. Here are two simple fixes you can use:
Solution 1: Make the iframe a Block Element
Update your CSS for the #video selector to add display: block—this tells the browser to treat the iframe as a block-level element, which will respond to margin: auto correctly:
#video { display: block; margin: 0 auto; /* Shorthand for top/bottom 0, left/right auto */ }
This is the most straightforward fix, and it won't affect other elements on your page.
Solution 2: Center Using a Parent Container (For Inline-Block Behavior)
If you want to keep the iframe as an inline-block element (for example, if you need to add other inline content next to it), wrap it in a container div and use text-align: center on the container:
Updated HTML:
<body> <header id="header">SCHIFRIN'S SPROCKETS <nav id="nav-bar"> <!-- Fixed your typo here: id="nav-bar" instead of id:="nav-bar" --> <ul> <li><a class="nav-link" href="#">LINK 1</a></li> <li><a class="nav-link" href="#">LINK 2</a></li> <li><a class="nav-link" href="#">LINK 3</a></li> </ul> </nav> </header> <img src="./logo.png" alt="Schifrin's Sprockets Logo" id="header-img"> <div class="video-wrapper"> <iframe id="video" width="560" height="315" src="https://www.youtube.com/embed/M-MKbRSSHG8" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> </div> </body>
Corresponding CSS:
.video-wrapper { text-align: center; }
Quick Note:
I also fixed a small typo in your HTML: your <nav> had id:="nav-bar" instead of id="nav-bar"—that could cause issues with any CSS/JS targeting the nav bar later on!
Either of these solutions will get your YouTube video centered perfectly. Let me know if you run into any other snags!
内容的提问来源于stack exchange,提问作者jamieschifrin

