Skip to content Skip to sidebar Skip to footer

Centre A Overflowing Element About Its Container

I have:
div { width: 100%; height: 400px; overflow: hidden; } iframe { width: 940px; height: 400px;

Solution 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.


Solution 2:

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


Post a Comment for "Centre A Overflowing Element About Its Container"