3

我有一个单列布局,其中列是具有固定宽度的居中 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 左对齐。

4

5 回答 5

4

#wrapper {
  margin: 0 auto;
  width: 200px;
  background-color: #eee;
  position: relative;
  height: 200px;
}

#child {
  position: absolute;
  top: 0;
  left: 50%;
  margin: 0 0 0 -200px;
  width: 400px;
  background-color: #ddd;
}
<div id="wrapper">
  <div id="child">Child div</div>
</div>

jsFiddle

当一个元素溢出他的父元素时,它只向右溢出是正常的行为。例如,当您有一个比视口更宽的站点时,您不必向左滚动,而只需向右滚动。此解决方案基于绝对居中的 div,左边距为负(该值是他自己宽度的一半)。所以如果你知道这个元素的宽度,这个解决方案应该没问题。

在 FF 3.6、IE7 和 IE8 中测试

于 2010-10-18T11:09:34.387 回答
3

我对 Justus 的解决方案做了一个变体。我在内部元素中使用了 50% 的负边距,而不是相对定位。

#wrapper {
    margin: 0 auto;
    padding: 10px 0 10px;
    width: 200px;
    background-color: #eee;
}
#child {
    margin: 0 -50%;
    width: 400px;
    background-color: #ddd;
}

这样您就不需要提前知道元素的大小。

于 2010-10-18T11:31:26.220 回答
0

我不是 100% 确定,但尝试给父元素一个位置设置为relative和子absolute然后设置topleft并相应地设置width/height子 div 的属性。

于 2010-10-18T11:02:19.873 回答
0

这就是我解决它的方法:

http://jsfiddle.net/WPuhU/1/

还要注意滚动条(如果您的窗口视图小于溢出的 div,它们不会出现)。自动将溢出的 div 居中。

CSS:

#center-3 {height:40px;background-color: #999;}
#center-1 {height:20px;top:10px;background-color: #aaa;}

/* the necesary code */
body {width:100%;margin:0;}
#center-4 {
    width: 100%;
    overflow:hidden;  
    /* remove the next 2 line for a normal flow */
    position: absolute;
    z-index: -1;
}
#center-3 {
    position: relative;
    margin: 0 auto;
    width: 200px;
}
#center-2, #center-1 {
    position: relative;
    width: 400px;
}
#center-2 {
    left: 50%;
}
#center-1 {   
    left: -50%;
}

html:

 <div id="center-4">
    <div id="center-3">
        <div id="center-2">
            <div id="center-1"></div>
        </div>
    </div>
</div>
<div id="other-stuff">Here comes the other stuff above.</div>
于 2013-06-08T17:27:29.990 回答
0
#parent {
  position: relative;
  width: 100px;
  overflow: visible;
}

#child {
  width: 400px;
  position: absolute;
  left: 50%;
  transform: translateX(-50%);
}
于 2016-02-23T17:50:04.150 回答