开发者

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. Is there a way to do this in CSS?

I considered absolutely positioning the h3, but I don't know the size from the edge开发者_Python百科 of the screen to the edge of the div (where I want it to be) since the div is centered.


On this page, I used Firebug to change the question title's css.

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

This is what happened:

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


(source: zastica.com)

There is a #question-header div that only extends to the top of the question ("I have a 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.

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; } prevents the page width from getting really big due to the padding.


Unfortunately what you are trying to do is impossible with plain CSS as you need to know the distance to the right edge. Absolute positioning would then work just fine. Of course, you can do this easily using some JavaScript, and even easier if using jQuery:

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

And in CSS:

h3 {
    position: absolute;
    ...
}


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.

Seems like you may just want to reorganize your HTML to make this possible.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜