考虑下面的例子:(现场演示)

HTML:

<div>div</div>
<iframe></iframe>

CSS:

div, iframe {
    width: 100px;
    height: 50px;
    margin: 0 auto;
    background-color: #777;
}

结果:

为什么iframe不像div一样集中对齐?我怎么把它放在中间?


当前回答

HTML:

<div id="all">
    <div class="sub">div</div>
    <iframe>ss</iframe>
</div>

CSS:

#all{
    width:100%;
    float:left;
    text-align:center;
}
div.sub, iframe {
    width: 100px;
    height: 50px;
    margin: 0 auto;
    background-color: #777;

}

其他回答

根据http://www.w3schools.com/css/css_align.asp,将左右边距设置为auto指定它们应该平均分割可用的边距。结果是一个居中的元素:

margin-left: auto;margin-right: auto;

将iframe居中的最佳方法和更简单的方法是:

<p align="center"><iframe src="http://www.google.com/" width=500 height="500"></iframe></p>

其中宽度和高度将是你的HTML页面中的iframe的大小。

<iframe src="https://www.facebook.com/plugins/page.php?href=https%3A%2F%2Fwww.facebook.com%2FRishabh-Cars-Jodhpur-110479104559774&tabs=timeline&width=500&height=1200&small_header=false&adapt_container_width=true&hide_cover=false&show_facepile=true&appId" width="500" height="1200" style="border:none;overflow:hidden;display:block;margin:0 auto;"6" allowfullscreen="true" allow="自动播放;clipboard-write;加密介质;画中画;合伙分成应得的" > < / iframe >

使用它和嵌入facebook在iframe中心的HTML页面

对齐iframe元素的最简单代码:

<div align="center"><iframe width="560" height="315" src="www.youtube.com" frameborder="1px"></iframe></div>

如果你不能访问iFrame类,然后添加下面的css包装div。

<div style="display: flex; justify-content: center;">
    <iframe></iframe>
</div>