'center a block with css using natural width of first line
I have text that I would like to display like this:
SOME HEADING TEXT
And then a bunch
of text under
that wrapped to
the width of the
heading.
What I mean is, I want a heading with some body text underneath. I want the text left-justified within this block. I want the width of the block to be defined by the width of the heading. Then I want the whole block centered within its parent.
If I knew that the heading was, say, 100 pixels, I could write:
<div style="width: 100px;margin:0 auto">
etc.
But I don't know the width of the heading. Even if it was static and I measured it, I would think this would be unreliable on different browsers, if the user changes his font size, etc.
I tried saying width:0 and putting  's into the heading. The heading displayed fine but the body text displayed with one word per line.
Any helpful hints?
Solution 1:[1]
You can accomplish what you're trying to do by absolutely positioning the text within the containing header element.
HTML:
<h1>
SOME HEADING TEXT
<span>
And then a bunch
of text under
that wrapped to
the width of the
heading.
</span>
</h1>
CSS:
h1 { display: inline-block; position: relative; }
h1 span { text-align: center; display: block; position: absolute; font: 14px/20px Helvetica, sans-serif; }
Fiddle: http://jsfiddle.net/ftkdD/1/
*Note: I've only tested this in Firefox. Also, it's important to note that the element height may become an issue if there is content set below the element as to clear the height, you'll need to apply bottom margin or padding since the absolute positioned text won't have any bearing on the elements overall height. As you can see here: http://jsfiddle.net/ftkdD/2/ *
Solution 2:[2]
Does this fiddle look like what you want?
CSS:
#main{
width: 200px;
height: 50px;
margin: 0 auto;
background: red;
}
#header{
background: blue;
}
HTML:
<div id="header">
<div id="main">
</div>
</div>
Solution 3:[3]
Nowadays we can do something like this:
HTML:
<body>
<h1>SOME HEADING TEXT</h1>
And then a bunch of text under that wrapped to the width of the heading.
</body>
CSS:
h1 {
width: max-content; } /* Natural width without wrapping. */
body {
margin: 0 auto; /* Centered left and right. */
width: min-content; } /* Squeezed to the minimum. */
Result:
· · · · · · · · · · · · · · · · ·
· SOME HEADING TEXT ·
· ·
· And then a bunch ·
· of text under ·
· that wrapped to ·
· the width of the ·
· heading. ·
· ·
· ·
· · · · · · · · · · · · · · · · ·
See: CSS box sizing values, min-content and max-content.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | sbeliv01 |
| Solution 2 | What have you tried |
| Solution 3 | Michael Allan |
