CSS3: Auto Hyphenation for Text-Elements
In browsers we do not have the ability to automatically hyphenate continuous text. This is an issue when you are using text-align: justify;
for instance because the text may look really bad.
I want to write about this topic because of the discussion that came up at the HTML5 Boilerpates issue-list and this blogpost at Fontdeck Blog.
The specification says:
Hyphenation means splitting words to improve the layout of paragraphs.
CSS3 Properties
CSS3 adds six properties to the list of useful thing. These are:
- The most important one is
hyphens
. More to this one later. - You can add dictionary-files with
hyphenate-resource
so the browser has a better chance to render your text with the right hyphenation. hyphenate-before
sets a minimum number of characters before the hyphenation.hyphenate-after
does the same ashyphenate-before
but for characters after the hyphenation.hyphenate-lines
defines about how many lines a hyphenated word is written at a maximum.- with
hyphenate-character
you can specify which HTML-entity should be used, e.g.\2010
.
The main property of this stack is hyphens
. It accepts one of three values: none
, manual
or auto
. The default one is manual
, where you can set hyphens via ­
. auto
it the better one for continuous text while words get split if possible and available. And none
does not hyphenate at all even if there is a character set for a possible line break in a certain word.
There is one thing you have to be aware of if you use this property: You have to define a lang
-attribute on an element that carries text that should be hyphenated.
I made this jsFidde where no lang
-attribute is set. It does not work in Firefox. With this attribute set, it works quite good in Firefox, too (thx to 91media).
Browsersupport
Currently hyphens
is supported in Safari 5.1 and Firefox 6. For Firefox 6 the lang-attribute must be set as mentioned above. Also it only supports english.
It is not working in Chrome 15.
You have to add some vendor-prefixes for support in browsers:
.element { -webkit-hyphens: auto; -moz-hyphens: auto; hyphens: auto; }
There is a polyfill for this. It’s working with JS and inserts the HTML special-char ­
where it fits. It supports many languages. This polyfill also uses the CSS-property where it is possible.
Edit:
Thanks to Ash for letting me know about my mistake using hyphen
instead of hyphens
.
Update
I just found this issue at the Modernizr issue-tracker where a test for the hyphens
-attribute is discussed. There is a test in the latest GitHub-Version for it. Search for csshyphens
.
Update 2: 12.11.2012
-webkit-hyphens
has now landed in Chrome Beta.