问题
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
widthis notautoandborder-left-width+padding-left+width+padding-right+border-right-width(plus any ofmargin-leftormargin-rightthat are notauto) is larger than the width of the containing block, then anyautovalues formargin-leftormargin-rightare, 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