0

我有一个居中的包装(固定宽度和动态填充)和一些 p-tags。这些标签的 backgroundColor 必须扩展到左侧的浏览器边框,但内容仍应保持在居中的内容区域内。

我设法用 JavaScript ( Example ) 做到了。

HTML:

<div>
    <p>asd</p><br>
    <p>asd</p><br>
    <p>asd</p>
</div>

JS:

$(document).ready(function() {
    $('p').css('padding-left', $('div').css('padding-left')).css('margin-left', "-" + $('div').css('padding-left'));
});

CSS:

div {
    width: 300px;
    background: green;
    padding: 0 calc(50% - 150px)
}

p {
    height: 50px;
    margin-bottom: 10px;
    background: blue;
    display: inline-block;
}

但我希望它只使用css。有没有办法在没有 JavaScript 的情况下获得这种行为?

FF、Chrome、iPad iOS5/6 Safari、IE9+ 必须支持。

/编辑:

感谢您到目前为止的回复。我在 p 元素上使用了 inline-block 以使其不会向右延伸,因为它应该像内联元素一样具有所需的最小宽度。但我仍然希望下一个元素位于新行中(如果有更好的解决方案,欢迎使用)

感谢 PaulvdTool,我设法找到了解决方案:http : //jsfiddle.net/EFhkH/2/

不过,如果您有更好的想法在 inline-block 之后强制换行,欢迎您

4

1 回答 1

1

你想要发生的事情(正如我从你的描述中得到的那样)甚至没有发生在你的小提琴中。当我调整屏幕大小时,蓝色不会停留在左侧。我尝试使用 CSS 制作它,并通过使用 :before 元素进行了一些管理。该效果仅适用于单行文本。

也许有人可以对此进行扩展。

CSS

#container {
    width: 300px;
    background: silver;
    margin: 0 auto 0 auto;
}
.text {
    width: 100%;
    background: gray;
}
.text:before {
    content: ".";
    background: gray;
    width: 50%;
    position: absolute;
    left: 0;
    z-index: -1;
    color: gray;
}

HTML

<div id="container">
    <div class="text"><p>line 1</p></div>
    <div class="text"><p>line 2</p></div>
    <div class="text"><p>line 3</p></div>
    <div class="text"><p>line 4a<br />line 4b</p></div>
/div>

http://jsfiddle.net/PaulvdDool/rtRQD/

编辑我通过添加一个点“。”作弊。在 before 元素中,否则背景不显示。我通过赋予它与背景相同的颜色使点不可见。

于 2013-06-03T13:35:35.637 回答