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 "10开发者_如何学JAVA0% + 12px" to make the inner element touch the right hand corner.
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">
<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>
An old question, but for those Googling in, you can now use vw
(device screen width) and position:relative
to achieve this:
.wrapper_div{
margin: 0 auto;
width: 50%;
padding: 20px;
}
.breakout_div{
position: relative;
width: 100%; /*Fallback for older browsers*/
width: 100vw; /*Percentage of full screen viewing width*/
left: calc(-50vw + 50%); /*Centres div*/
}
精彩评论