views:

122

answers:

1

If I have a 100% wide div element with 12 pixels of padding to the left and to the right, and I have an element inside the div that I want to span from one corner of the screen to another (bridging the 12 pixel gap), do I have any chance of "breaking out" of the surrounding div without using absolute positioning?

Using position:relative; left:-12px won't work alone, because the div is 100% wide and I can't specify "100% + 12px" to make the inner element touch the right hand corner.

+3  A: 

A pure CSS solution:

#breakout { margin-left: -12px; width: 100%; padding-left: 12px; padding-right: 12px; }

Tested working in FF 3.5 and IE8. Other browsers not tested. With IE7 or before it might be weird.

I think the reason this works is because the browser adds the tag width with it's white space (padding). In this case margin-left: -12px shifts the div to visually look like it's ignoring the parent's padding: 12px. At first I thought width: 100%; padding-right: 12px; alone would work, but it didn't. I realized this is because the box model being used. It didn't factor in the initial padding because it was collapsing with the parent's padding (or so I am assuming).

For reference here was my test page:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"&gt;

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <title>Hello</title>
    <style type="text/css">
        html, body { padding: 0; margin: 0; color: white; }
        #outer { padding: 12px; background-color: blue; }
        #breakout { background-color: red; margin-left: -12px; width: 100%; padding-right: 12px; padding-left: 12px; }
    </style>
</head>
<body>
    <div id="outer">
        <h3>Some content</h3>
        <div id="breakout">Breakout</div>
        <h3>More content</h3>
    </div>

</body>
</html>
T. Stone
Wow, this looks great. Will try it some time today and give feedback. I hope IE7 will play along because I *do* need it in this case...
Pekka
Cheers T.Stone, what I had not mentioned in my original question was the fact that inside the DIV, I have a WYSIWYG editor that needs to stretch the full width of the DIV, so padding is not an option. I played around a bit with negative margins and paddings, but I never managed to stretch the DIV on the right side so that the editor would stretch along. I will have to remove the padding, find a workaround there and give the div 100% "natural" width. Thanks anyway!
Pekka