CSS to constrain 960px inside a div?
At the moment I have this (standard) code whic开发者_开发技巧h gives me a full-width background but constrains the header to centered 960px:
<div style="background-color: #222">
<header style="width: 960px; margin: 0 auto;">
<h1>Site Title</h1>
</header>
</div>
Is there a way I can apply those to a single element in CSS, and avoid the div
altogether? I considered this jQuery hack to calculate and set left and right padding on header
but a pure CSS solution would be better.
Desired HTML:
<header>
<h1>Site Title</h1>
</header>
It might not be possible but thought I'd ask before dismissing it!
You can ditch the div wrapper in favor of :before
and :after
. Here's an article on it: http://css-tricks.com/9443-full-browser-width-bars/
The end of the article has a link to information on which browsers support :before
and :after
. For those that don't, you could use a javascript polyfill.
if it's for the whole page you can set the background on the <body>
otherwise I think you'll need to use a <div>
like you have.
Would something as this simple work?
header {
background-color: #222;
display: block;
width: 100%;
}
header h1 {
background: #fcc;
color: #000;
margin: 0 auto;
width: 960px;
}
Edit this jsFiddle: http://jsfiddle.net/t6wBv/2/
I take it this is HTML5 you're working with? There's no need to wrap a div around a header. This is one of the beautiful things about HTML5!
What I would do is give this particular header an ID, and stylize from there. For instance:
Your CSS file (or included CSS):
#title {
background-color: #222;
margin: 0 auto;
width: 960px;
}
Your HTML:
<header id=#title>
<h1>Site Title</h1>
</header>
This link kind of does the same thing you're looking to do!
Actually it is possible using just a single element. Thanks to the fact that padding in percentage refers to parent's width.
In fiddle I used div
but it should work with header
as well.
精彩评论