Auto center with CSS with one exception
I have a design like that: alt text http://img15.images开发者_Python百科hack.us/img15/8647/designiq.jpg
All my auto centered content has the following CSS:
width: 960px;
margin: 0px auto;
Inside this auto centered content is a DIV-Element that should have a width of the full browser width.
What's the best solution to make the 100%-DIV?
position: absolute /* or fixed */
is not that what I want to have,
because the content-height above the 100%-DIV is not every time the same.
Here is an example Code:
<html>
<head>
<title>Boxes</title>
<style type="text/css">
<!--
body {
margin: 0;
padding: 0;
}
* {
margin: 0;
padding: 0;
}
#wrapper {
width: 100%;
margin: 0 auto;
}
#wrapper div.width_960 {
width: 960px;
margin: 0 auto;
border-left: 2px #000 solid;
border-right: 2px #000 solid;
}
#wrapper div.width_full {
width: 100%;
background: #000;
}
-->
</style>
</head>
<body>
<div id="wrapper">
<div class="width_960">
<p>demo</p>
<p>demo</p>
<p>demo</p>
<p>demo</p>
<p>demo</p>
</div>
<div class="width_full">
<p>demo full</p>
<p>demo full</p>
</div>
<div class="width_960">
<p>demo</p>
<p>demo</p>
<p>demo</p>
<p>demo</p>
<p>demo</p>
</div>
</div>
</body>
</html>
Setting a width is a one-way in CSS; you instantly lose the information of the parent's width.
To put it in a nutshell: You can't re-set a div inside a constrained div to the window's width with CSS only. With JavaScript, and assuming that the parent has no overflow:hidden
, you could do this:
- set the child's width to window.innerWidth and
- set the child's left and right margin to -(window.innerWidth/2 - parentDivs_width)
like, e.g. for a window size of 800px:
#parent {
width: 300px;
margin: 0 auto;
}
#child {
/* set these with JS */
width: 800px;
margin: 0 -250px;
}
The more trivial solution is to move the child div out of its parent and position it and the parent with negative top and bottom margins. (position:absolute
won't work, because it's the same, you lose the information about the width.)
You can't have an element wider than it's parent. You have to put it out of the flow.
position:absolute
seems the answer, if you don't specify the top position it will take its position in the flow.
position:absolute;
width:100%;
left:0px;
It's a nasty ugly trick, but here is one way, without any Javascript.
Basically, you make a separate absolutely positioned background element sized to cover any possible window.
EDIT: Fixed to handle multiple lines.
div.FullWidth {
position:relative;
}
div.FullWidth .Background{
position: absolute;
left:-2048px;
z-index:-1;
width: 4096px;
height:100%;
background:#999;
}
div.FullWidth .Content {
text-align: center;
font-size:larger;
color: red;
}
<div class="FullWidth">
<div class="Background"> </div>
<div class="Content">
Hello!</div>
</div>
精彩评论