Centre a overflowing element about its container

强颜欢笑 提交于 2019-12-13 04:02:49

问题


I have:

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


div {
    width: 100%;
    height: 400px;
    overflow: hidden;
}
iframe {
    width: 940px;
    height: 400px;
    margin: 0 auto;
    display: block;
}

The iframe will overflow the div leading to a 'missing section' on the right. I need the Iframe centred such that this 'missing section' is the same both sides. Margin: 0 auto doesn't seem to cut it.

(The iframe is a video to put this into context)


回答1:


What about using a negative margin (as the half of the iframe width) as follows:

iframe {
    width: 940px;
    height: 400px;
    margin-left: -470px /* <-- 940px / 2 */
}

Or using position: relative; with left: -470px;.

margin: 0 auto will not work for the child which is wider than its parent. Even if you change the display property to block.

From the Spec (10.3.3 Block-level, non-replaced elements in normal flow):

If width is not auto and border-left-width + padding-left + width + padding-right + border-right-width (plus any of margin-left or margin-right that are not auto) is larger than the width of the containing block, then any auto values for margin-left or margin-right are, for the following rules, treated as zero.

If CSS3 is an option, you could set a position property for the iframe including a negative translateX to keep the element center when the parent resizes:

iframe {
  width: 940px;
  height: 300px;
  background-color: orange;

  position: relative;
  left: 50%; 
  transform: translateX(-50%);
}

WORKING DEMO

For the old browsers which don't support CSS3 transform, you'll need to add an additional element as a wrapper.

In this approach, the child (iframe in your case) is wrapped by another element called .wrapper as follows:

<div class="parent">
  <div class="wrapper">
    <div class="child"></div>
  </div>
</div>
.parent {
  width: 100%;
  height: 400px;
  overflow: hidden;
  position: relative;
}

.wrapper {
  position: absolute;
  left: 50%;
}

.child {
  width: 940px;
  height: 300px;  
  position: relative;
  left: -50%;
}

UPDATED DEMO.




回答2:


Iframe is an inline element. Add display: block; to let margin: 0 auto; work.



来源:https://stackoverflow.com/questions/21881441/centre-a-overflowing-element-about-its-container

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!