Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I center an inline-block/floated header with no extra markup?

Tags:

html

css

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)!

like image 630
joshnh Avatar asked Sep 02 '11 04:09

joshnh


People also ask

How do you center an inline block?

Inline block divs can be centered by applying text-align:center to their parent.

How do I center an inline block in HTML?

Try using this: margin: 0 auto; Or text-align: center; on the parent <div> ...

How do you center inline items?

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 .

How do I center a block display?

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.


2 Answers

Solved using display: table; on the heading (with margin: 0 auto;).

like image 134
joshnh Avatar answered Nov 15 '22 20:11

joshnh


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/

like image 26
sandeep Avatar answered Nov 15 '22 21:11

sandeep