Search code examples
htmlcssiframe

My iframe will not center when sizing in my CSS doc but will when resize in HTML doc. I want it to be resized in CSS doc for good practice


So I have my iframe but left aligned but it wont center.

.iframeContainer {
    display: inline-block;
    justify-content: center; /* Center the iframe horizontally */
    align-items: center;
    width: 1067px;
    height: 600px; 
}
<div class="iframeContainer">
    <iframe width="100%" height="100%" src="https://www.youtube.com/embed/vFO0_PA_NAg?si=VeD7R53zMk8l3yw8" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>
</div>

when I try and resize the iframe in the html Doc it works. For example:

<div class="iframeContainer">
        <iframe width="1067px" height="600px" src="https://www.youtube.com/embed/vFO0_PA_NAg?si=VeD7R53zMk8l3yw8" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>
</div>

then the CSS page would just like

.iframeContainer {
    display: flex;
    justify-content: center; 
    align-items: center;
}

I also tried putting the margin as auto... that didn't work either.

now I could be wrong so bear with me I am new to the coding world but I beilve an iframe is a block element so I am bewildered that it works as a flex. I know it's good practice keep elements consistent so any help would be greatly appreciated.


Solution

  • First your display inline-block wont work with align-items: center; and justify-content. just remove them with the display: inline-block and add margin:auto and it will work you will have the horizontal alignment: check it full page in the snippet below. As iframeContainer div display as block (not inline block) so we need to use margin: auto

    .iframeContainer {
        width: 1067px;
        height: 600px; 
        margin: auto;
    }
    <div class="iframeContainer">
            <iframe width="100%" height="100%" src="https://www.youtube.com/embed/vFO0_PA_NAg?si=VeD7R53zMk8l3yw8" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowfullscreen></iframe>
    </div>