【问题标题】:CSS - full width element within narrow parent?CSS - 窄父级中的全宽元素?
【发布时间】:2014-05-04 14:14:34
【问题描述】:

我有一篇 960 像素宽的博文。

我希望这篇博文的部分内容覆盖 100% 的视口(从左:0 到右:0)。使用绝对定位相当容易,但使用这种方法不可能清除这些 100% 宽的元素。

HTML:

<div class="wrapper">
    <h1>A header</h1>
    <p>Some content.</p>
    <div class="out">
        <blockquote>Some blockquote.<br/> Another line.<br/>And another.</blockquote>
    </div>
    <p>Clears don't work here and this content is invisible :( </p>
    <p>And this sucks :( </p>
    <div class="out">
        <blockquote>And different blockquote.<br/> Another line.<br/></blockquote>
    </div>
    <p>Also this is behind blockquote as well.</p>
</div>

CSS:

body {
    position: relative;
}

.wrapper {
    margin: 0 auto;
    padding: 15px;
    background: #eee;
    width: 400px;
    height: 1000px;
}

.out {
    position: absolute;
    right: 0;
    left: 0;
    padding: 15px;
    background: #aaa;
    width: 100%:
}

blockquote {
    margin: 0 auto;
    width: 400px;
}

这是一个演示:

http://jsfiddle.net/2rC2S/1/

注意:所有块引用都有不同的高度,所以我不能为它们设置它。我不想使用 JavaScript(因为获取元素高度、设置 this 和繁荣相当容易,但谁用 JS 呈现内容?!)。

【问题讨论】:

  • 你可以试试简单的 .out {background: #AAAAAA;边距:0 -15px; padding: 15px;} 你在找这样的东西吗jsfiddle.net/2rC2S/3

标签: css position width absolute clearfix


【解决方案1】:

您可以通过使用如下伪选择器之前和之后来做到这一点

.out:before, .out:after {
     content:"";
     background: black;
     position: absolute;
     top: 0;
     bottom: 0;
     width: 9999px;
 }
 .out:before {
     right: 100%;
 }
 .out:after {
     left: 100%;
 }

http://jsfiddle.net/kM3Gf/

你可以在这里找到原创文章http://css-tricks.com/examples/FullBrowserWidthBars/

我仍然不确定浏览器的兼容性!

【讨论】:

  • width: 9999px ?为什么要浪费这么多内存? 50vw就够了
  • 嗯,这是因为现在设备宽度和屏幕分辨率各不相同,所以它适合所有用途。我也很好奇我们是否使用 width: 9999px 它会与内存相关还是对网页性能有多大影响。你能提供任何链接来证明提前谢谢
  • 这很有希望,但不幸的是,当您将包装器宽度设置为 x px 时似乎根本不起作用(仅适用于 %):(
  • @Pravin:我没有测试它,但考虑到您正在强制浏览器绘制一个 9999 像素的框,我认为这是一个公平的假设。使用 50% 的视口有什么问题? jsfiddle.net/sGJYe
  • jsfiddle.net/2rC2S/8 已更新 @ onetrickpony 建议,但我不知道大众单位兼容性 @Wordpressor 它也更新了 .wrapper dows 上的像素宽度,它有帮助吗?
【解决方案2】:

也许您可以避免设置包装器的宽度,而是为每个内容元素设置它?

绝对定位的元素不会占用文档中的空间,因此不会下推任何内容。

看到这个DEMO

.wrapper h1, .wrapper p {
    margin: 0 auto;
    padding: 15px;
    background: #eee;
    width: 400px;
}

【讨论】:

    猜你喜欢
    • 2014-08-04
    • 1970-01-01
    • 2011-11-02
    • 2017-11-11
    • 2012-06-02
    • 2016-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多