Center for aligning text and aligning minimum and maximum width

Violin: 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 maximum and minimum widths, the sentence is centered perfectly, but I want it to be centered rather than occupying the entire width. Why is the text aligned left when I add width limits?

+7
html css
source share
2 answers

The text inside h1 actually centered, but it is centered within a 100px width box . If you want h1 to float in the middle of the window , add margin:0 auto; . The main reason left h1 alignment is related to the display:box property.

 <h1>this is a really, really long sentence</h1> <style type="text/css"> h1 { min-width:100px; max-width:100px; text-align:center; margin:0 auto; } </style> 
+10
source share

This is because the word "sentence" has a width of more than 100 pixels and by default the text only breaks into spaces. Change it to the following [although this may make reading difficult]:

 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 can center it using the field: 0 auto; - but the word sentence will still not be concentrated within h1.

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

If you want to pin each word on a new line and keep the longer words centered, you can 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 wherever a line break is in html. You still have to make the whole element as wide as the widest word.

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

0
source share

All Articles