(大)div在较小的div内水平居中。纯CSS解决方案可能吗?

时间:2013-11-01 08:05:57

标签: css html css-position centering

我想让“Shadow”div在“Wrapper”内水平居中。由于宽度:100%,“Wrapper”的特定宽度未知,因此还不知道是否“Shadow”div大于或小于其容器。

这甚至可能吗?我想不出任何解决方案。自动保证金不起作用。 仅限CSS和HTML

示范代码:

HTML:

<div class="Wrapper">
  <div class="Shadow">some content</div>
  <div class="Content">some content</div>
</div>

CSS:

.Wrapper{ width: 100%; height: 100%; position: relative; background: url(path) top center no-repeat; max-width: 1520px; max-height: 1050px; overflow: hidden; }
.Shadow{ width: 1520px; height: 1050px; }
.Content{ position:absolute; top: 20px; left: 20px; width: 800px; height: 500px; }

1 个答案:

答案 0 :(得分:4)

你可以尝试这样的事情: DEMO

使用margin-left: 50%将子项移动到包装器的中心,然后使用left将子项向左移动一半宽度。

我的例子中相关的CSS行:

.wrapper {
    position:relative;
    /* other properties */
}
.shadow {
    position: absolute;
    margin-left: 50%;
    width: 400px;
    left: -200px;
    /* other properties */
}

或者:

您可以使用transform:translate(-760px);代替left - 然后您不需要绝对定位阴影元素,请参阅此DEMO