How do I center an inline-block/floated header with no extra markup?
I have a variable width header that must have a background color that is as wide as the text (no wider). The only way I can think of doing this (with no extra markup) is to set the display to inline-block or float it to the left开发者_StackOverflow. The problem then though is that I cannot center the header (another requirement).
The closest I have got so far is by setting position: relative;
on a floated header, pushing it across 50% from the left and then pulling it back 25% with negative margin, however this does not consistently center the header. It must remain in the flow of the document so position: absolute;
is another no-go.
If you are aware of a way to do this using CSS only with no extra markup please let me know (pseudo-elements are fine, I'm not hassled about IE7 support)!
Solved using display: table; on the heading (with margin: 0 auto;).
you can give text-align:center;
to the body
as a global arrtibute & give display:inline-block
to your header
div. So,it's center your dynamic width
in center
like this :
CSS:
body{margin:0; padding:0;text-align:center}
p{text-align:left;}
.header{background:red;display:inline-block;}
Check this example http://jsfiddle.net/vpcXS/
replace the p tag with center as my markup is
<div id="header">
<center>hello</center>
</div>
and it's CSS is
body{
width:100%;
}
#header{
text-align:center;
}
#header center{
display:inline-block;
background:red;
}
精彩评论