21
votes

The fiddle: http://jsfiddle.net/uK7w6/1/

<h1>this is a really, really long sentence</h1>

h1 {
    min-width:100px;
    max-width:100px;
    text-align:center;
}

If you get rid of the max and min width, the sentence centers fine, but I want it to center as well as not take up the whole width. Why does the text align left when I add width constraints?

3
It doesn't, for me. Chrome 32.0.1700.76Jon Newmuis
Works fine for me in Firefox 26.Sadiq
Setting both min and max width to the same value is the same as just setting width.powerbuoy
^cool thanks, i didn't know that.mango

3 Answers

43
votes

The text within the h1 is actually centered, but it is centered within a 100px width box. If you want the h1 to float in the middle of the window then add a margin:0 auto;. The primary reason that the h1 is aligned to the left has to do with the display:box property.

h1 {
  min-width:100px;
  max-width:100px;
  text-align:center;
  margin:0 auto;
}
<h1>this is a really, really long sentence</h1>
0
votes

Thats because the word 'sentence' is more than 100px wide and by default text only breaks at spaces. Change it to the following [although it can make it harder to read]:

h1 {
  min-width:100px;
  max-width:100px;
  text-align:center;
  -ms-word-break: break-all;
  word-break: break-all;
  // Non standard for webkit
  word-break: break-word;

  -webkit-hyphens: auto;
  -moz-hyphens: auto;
  hyphens: auto;
}

Or make it wider. You could center it with margin: 0 auto; - but the word sentence still wont be centred within the h1.

Edit: This may be what you're actually trying to achieve.

If you want to force each word on a new line and keep the longer words centered you could do the following:

h1 {
  min-width:200px;
  max-width:200px;
  text-align:center;
  white-space: pre-line;
}

<h1>this 
is 
a 
really, 
really
long
sentence</h1>

white-space: pre-line; will put a line break where ever there is a line break in the html. You will still have to make the whole element as wide as the widest word though.

http://jsfiddle.net/uK7w6/1/

0
votes

Heading1 is a block-level element. But text-align property in CSS is used for aligning the inner content of a block element(inline and inline-block elements)
So your text-align won't do anything to a block element itself but really can center the contents in the block element. Check this out:

The Reason Why Max-Width MessUp Text-align

* {
  margin:0;
  padding:0;
}
.container {
  width: 100%;
  height: 100vh;
  border: 1px solid red;
  text-align: center;
}
.item {
  border: 1px solid red;
  background: gray;
  height:5vh;
}
.withMaxWidth {
  max-width: 60%;
}
.inline-block {
  display:inline-block;
  
}
<article class="container">
  <p class="item">A normal block element seems centered</p>
  <p class="item withMaxWidth">A max-widthed block element</p>
  <p class="item inline-block">An inline-block element centered by text-align</p>
</article>