我在我的页面上制作了一个视频响应,但现在我无法将它居中

I made a video on on my page responsive, but now I can't center it

我正在为 freecodecamp 做我的第三个项目,制作一个产品登陆页面。我嵌入了一个视频,并在网上查找了一些代码以使其响应。我应用了它,但现在,无论我尝试了什么,我都无法让视频居中。我什至尝试制作一个 flexbox 来使用 justify-content 和 center。

这是相应的 HTML 和 CSS 代码,我认为它们与我的视频居中有关(在此示例中没有添加任何尝试居中的内容):

HTML

<section id="video">
<iframe width="560" height="315" src="<!-- my embed src here -->" frameborder="0" allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture" allowfullscreen>
</iframe>
</section>

CSS

#video {
  padding-bottom: 55%;
  position: relative;
  padding-top: 30px;
  height: 0;
  overflow: hidden;
  margin-top: 50px; 
}
#video iframe,
#video object,
#video embed {
  position: absolute;
  top: 0;
  left: 0;
  width: 60%;
  height: 60%;
}

我对任何编码语言都很陌生,一直在关注 freecodecamp。我自己能够弄清楚如何将视频嵌入 HTML,但我从在线资源中获得了 CSS 代码。我尝试添加

display: flex;
justify-content: center;

到 CSS 的 #video 部分,但它没有做任何事情。在整个项目中我一直很沮丧,似乎我尝试的任何合乎逻辑的事情都没有做任何事情。我希望这会变得更好。

将CSS的以下代码替换为

#video iframe,
#video object,
#video embed {
  position: absolute;
  top: 0;
  left: 0;
  width: 60%;
  height: 60%;
}

用这个

#video iframe,
#video object,
#video embed {
  position: absolute;
  left: 50%;
  right: 50%;
  transform: translateX(-50%);
  width: 60%;
  height: 60%;
}
 #video embed {
  position: absolute;
  top: 0;
  left: 0;
  width: 60%;
  height: 60%;
}

收件人:

#video embed {
   position: absolute;
   top: 0;
   left: 0;
   right: 0;
   width: 60%;
   height: 60%;
   margin: 0 auto;
}

您的视频包装器需要 flexbox 样式。所以这应该有效:

#video {
  padding: 50px;
  display: flex; // flexbox on the container
  align-items: center; // centers items against the main flex axis, vertically by default
  justify-content: center; // centers items on the main axis, horizontally by default
}
#video iframe {
  // nothing else needed on the iframe to achieve centering on the page. This will need more styles if you have more than one item in the flex container, ie more than one iframe in the #video container.
}

您应该能够简单地通过给它动态边距来使您的视频包装元素居中:

<styles>
    #video {
        padding-bottom: 55%;
        position: relative;
        padding-top: 30px;
        height: 0;
        overflow: hidden;
        margin-top: 50px;

        /*display item as block element */
        display: block;

        /* align left and right margins dynamically throwing you right in the middle */
        margin-left: auto;
        margin-right: auto

        /* width and/or max-width must tell us how big video wrapper can really be */
        width: 100%;
        max-width: 500px;
    }
</styles>

如果您的视频仍未居中,则表示其父元素的宽度设置不正确。