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. 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)!
Inline block divs can be centered by applying text-align:center to their parent.
Try using this: margin: 0 auto; Or text-align: center; on the parent <div> ...
To center an inline element like a link or a span or an img, all you need is text-align: center . For multiple inline elements, the process is similar. It's possible by using text-align: center .
After setting the “display: block” property, we can make our image to block element. It can be centered using “margin: auto” property. Note: The body tag has been set to the “text-align: center” property. We know that it is not affecting the block elements.
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With