0

我有一个固定宽度的容器 div。我希望其中一个子元素与浏览器窗口一样宽。我会将子元素从父容器中取出,但它会破坏功能。我试过这个:

.parent { width: 960px; position: relative; left: 50%; margin-left: -480px; }
.child { position: absolute; left: 0; right: 0; width: 100%; }

对此:

<body>
    <div class="parent">
        <div class="other">This div's positioning is absolute but dependent on the parent element's relative positioning</div>
        <div class="child>This div wants to be centered and as wide as the browser window</div>
    </div>
</body>

但这不起作用。有什么我可以做的吗?

4

3 回答 3

0

相对于任意容器/祖先(不一定是直接父级)设置块的大小是 CSS 不支持的必需功能之一。使用现有 CSS 功能的典型解决方案是将整个页面划分为具有自己居中子元素的多条水平线。

例如,在以下示例中,第二个块的宽度为 100%,而第一个和第三个块的宽度有限且居中:

<div class="line" id="first"><div>First line (centered)</div></div>
<div class="line" id="second">Second line (100% width)</div>
<div class="line" id="third"><div>Third line (centered)</div></div>
.line > DIV {
    margin: 0 auto;
    width: 960px;
}

#first > DIV {background: #f00; }
#second      {background: #0f0; }
#third > DIV {background: #00f; }

现场演示

于 2013-04-09T22:27:47.080 回答
0

你到底想完成什么?usingposition:relative将导致 using 的任何子元素position:absolute从父元素的左上角像素开始。如果您删除它,则 divposition:absolute内的任何元素.parent都将返回到从 div 的左上角像素开始body

假设您使用.parentdiv 的相对定位来进行放置,而不是子元素定位(应该如何使用),您可以像这样完成同样的事情:

<body>
    <div class="parent">
        <div class="child">stuff</div>
    </div>
</body>

body { text-align: center; }
.parent { width: 960px; margin: 0 auto; text-align: left;}
.child { position: absolute; left: 0; right: 0; width: 100%; }

带有大小和颜色属性的 jsfiddle 可帮助说明此处的内容:http: //jsfiddle.net/Ncy5Y/

于 2013-04-09T22:13:37.463 回答
0

如果您想保留当前的 ​​CSS 配置,您应该尝试使用 JQuery 执行此操作:

$(function() {
    $('.child').width($(window).width());
});

编辑:

这应该可以工作并且还可以响应窗口宽度:

$(function() {
    $('.child').width($(window).width());
    $(window).resize(function(){
        $('.child').width($(window).width());
    });
});

如果需要,您可以创建一个包含重复行的函数。

编辑2:

要将元素向左对齐,请使用以下命令:

$(function() {
    position();
    $(window).resize(function(){
        position();
    });
})

function position() {
    $('.child').width($(window).width()).offset({left: 0, top: 0});
}
于 2013-04-09T22:15:02.190 回答