简体   繁体   English

如何将元素的背景扩展到其容器之外?

[英]How can I extend the background of an element beyond its container?

I have a div that contains an h3 tag, and i want the h3's background to extend beyond the containing div tag to the edge of the page. 我有一个包含h3标签的div,我希望h3的背景超出包含div标签到页面边缘。 Is there a way to do this in CSS? 有没有办法在CSS中这样做?
I considered absolutely positioning the h3, but I don't know the size from the edge of the screen to the edge of the div (where I want it to be) since the div is centered. 我认为绝对定位h3,但我不知道从屏幕边缘到div边缘的大小(我希望它的位置),因为div居中。

On this page, I used Firebug to change the question title's css. 在这个页面上,我使用Firebug来改变问题标题的CSS。

#question-header h2 {
    background:lime;
    margin-bottom:-1000px;
    padding-bottom:1000px;
}

This is what happened: 这就是发生的事情: 替代文字
(source: zastica.com ) (来源: zastica.com

There is a #question-header div that only extends to the top of the question ("I have a div..."). 有一个#question-header div只能扩展到问题的顶部(“我有一个div ...”)。 The key is having a large padding-bottom and a large (negative) margin-bottom. 关键是有一个大的填充底部和一个大(负)边缘底部。

This also works for side-to-side backgrounds. 这也适用于侧面到背景。 You just have to make sure the container doesn't have overflow: hidden set. 您只需要确保容器没有overflow: hidden set。

Edit: To get this effect left and right, set: 编辑:要左右移动此效果,请设置:

html {
    overflow-x: hidden;
}

#question-header h2 {
    padding: 0 1500px;
    margin: 0 -1500px;
}

The html { overflow-x: hidden; } html { overflow-x: hidden; } html { overflow-x: hidden; } prevents the page width from getting really big due to the padding. html { overflow-x: hidden; }防止页面宽度变得非常大,由于填充。

An elements background cannot extend beyond it's bounding box. 元素背景不能超出它的边界框。

You could in some cases extend the H3 beyond it's container by setting negative margins, but you would need the exact width of the page. 在某些情况下,您可以通过设置负边距将H3扩展到容器之外,但是您需要页面的确切宽度。

Seems like you may just want to reorganize your HTML to make this possible. 好像您可能只想重新组织HTML以实现这一点。

Unfortunately what you are trying to do is impossible with plain CSS as you need to know the distance to the right edge. 不幸的是,你需要知道通过简单的CSS,你需要知道到右边缘的距离。 Absolute positioning would then work just fine. 然后绝对定位可以正常工作。 Of course, you can do this easily using some JavaScript, and even easier if using jQuery: 当然,您可以使用一些JavaScript轻松完成此操作,如果使用jQuery则更容易:

$(function() {
    $('h3').each(function() {
        $(this).width($(window).width() - $(this).offset().left);
    });
});

And in CSS: 在CSS中:

h3 {
    position: absolute;
    ...
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM