Reputation: 87271
Is it possible to center a multiline <div>
horizontally, while its contents remain aligned to the left (text-align:left
), without specifying display:table
and without having to know the pixel width of the <div>
(it should become as wide as needed)? It has to work in Firefox 3 and Chrome.
I have the following working solution which contain a <div>
inside another <div>
, so I'm only looking for a solution which doesn't need an inner <div>
.
<style type="text/css">
div.showtitle {
margin-left:auto;
margin-right:auto;
display:table;
}
div.showtitle > div {
background:#7777ff;
color:ffffff;
text-align:left;
padding:.34em;
font-size:140%;
}
</style>
<div class="showtitle"><div>Centered div<br>with left-aligned text</div></div>
FYI The reason why display:table
and font-size:140%
cannot be combined in the same <div>
is that in Chrome it has a bad effect on the line height of the font-size
of its container gets changed in JavaScript.
Upvotes: 4
Views: 2895
Reputation: 87271
It seems that it's impossible to do the center alignment without display:table
or an inner <div>
or specifying the width of the <div>
.
Upvotes: 0
Reputation: 63519
<style>
#outer {
text-align: center;
}
#inner {
display: -moz-inline-box; /* Firefox < 3 */
display: inline-block; /* Standards */
/* IE < 8, inline + hasLayout */
*display: inline;
*zoom: 1;
text-align: left;
}
</style>
<div id="outer"><div id="inner">Your centered content here</div></div>
Upvotes: 1
Reputation: 78840
All you should really need is to set a width on the div
and set auto margins. You don't need an outer div
; the element will be horizontally centered in whatever block-level element it's contained in, including the body.
.showtitle
{
with: 350px;
margin-left: auto;
margin-right: auto;
text-align: left;
}
Update:
It's unclear what you mean by wanting the width of the div to be dynamic and yet be multi-line. At what point will the content wrap, or are you wanting to only do manual line breaks? If you're doing content wrapping, would the div stick to 100% once it has to wrap? If you don't want the width at 100%, what should its maximum width be set to?
You mentioned that you wanted the content left-aligned, yet if it's contained in a centered block that automatically sizes to fit, then you're basically asking for a centered inline element. If you want the content to wrap to multiple lines and be left-aligned, you'll either have to specify a width or be fine with 100% width. If you're wanting the lines of text to auto-balance and then to have the container resize to fit, I believe you're out of luck as far as what CSS offers.
Upvotes: 2
Reputation: 10485
I might be reading this wrong, but you should be able to just apply margin: 0 auto; width:960px;
to your showtitle div and be golden.
Upvotes: 1
Reputation: 22438
<div class="showtitle">Centered div<br>with left-aligned text</div>
with
.showtitle {
margin: 0 auto;
width: ...;
}
should work fine in Firefox and Chrome.
Upvotes: 1