将一个 div 居中,使其在另一个居中的 div 中溢出其父级
我有一个单列布局,其中该列是一个具有固定宽度的居中 div。我想在列中放置一个更宽的 div,使其溢出其父级,但将其置于父级的中心。从概念上讲,如下所示:
<div style="width: 100px; margin: 0 auto; overflow:visible;" id="parent">
<div style="width: 400px; margin 0 auto;" id="child"></div>
</div>
只要子 div 比其父 div 薄,居中就起作用,但一旦它变大,它总是由于某种原因与父 div 左对齐。
I have a single column layout where the column is a centered div with a fixed width. I want to place a wider div within the column which overflows it's parents, but center it within the parent. Conceptually something like the following:
<div style="width: 100px; margin: 0 auto; overflow:visible;" id="parent">
<div style="width: 400px; margin 0 auto;" id="child"></div>
</div>
The centering works as long as the child div is thinner than its parent, but once it gets larger, it always aligns left with the parent for some reason.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
jsFiddle
当元素溢出其父元素时,它只向右溢出是正常行为。例如,当您的网站比视口更宽时,您永远不需要向左滚动,而只需向右滚动。该解决方案基于绝对居中的 div,具有负左边距(该值是其自身宽度的一半)。所以如果你知道这个元素的宽度,这个解决方案应该没问题。
在 FF 3.6、IE7 和 IE8 中测试
jsFiddle
When an element overflows his parent, it is normal behaviour that it only overflows to the right. When you, for example, have a site that is wider then the viewport, you never have to scroll left, but only to the right. This solution is based on a absolute centered div, with a negative left margin (that value is the half of his own width). So if you know the width of this element, this solution should be fine.
Tested in FF 3.6, IE7 and IE8
我制作了 Justus 解决方案的一个变体。我在内部元素中使用了 50% 的负边距,而不是相对定位。
这样您就不需要提前知道元素大小。
I made a variation of Justus' solution. Instead of relative positioning, I used a negative margin of 50% in the inner element.
This way you don't need to know the element sizes ahead of time.
我不是 100% 确定,但尝试将父元素的位置设置为
relative
和子元素absolute
,然后设置top
、left相应的子 div 的
和width/height
属性。I am not 100% sure but try giving the parent element a position set to
relative
and childabsolute
and then settop
,left
andwidth/height
properties for the child div accordingly.这就是我解决它的方法:
http://jsfiddle.net/WPuhU/1/
另外要小心滚动条(如果您的窗口视图小于溢出的 div,则滚动条不会出现)。自动将溢出的 div 居中。
css:
html:
This is how I solve it:
http://jsfiddle.net/WPuhU/1/
Also take care of the scrollbars(they do not appear if your window view is smaller then the overflowing div). Auto centers the overflowing div.
css:
html: