Thursday 1 November 2012

CSS3: use hyphens to control text flow

   


It seems that I somehow discovered CSS3 lately. I am aware that recently I wrote a lot about it, but today I feel like sharing the following info.
Have you ever needed to control the text flow in web page?
With the CSS3 hyphens property we can really do interesting things.

An intro
We can use hyphens to automatically hyphenate a justified text, giving it the same flow as we can see on books, magazines and newspapers.

So nothing really new, isn't it? Well, not really. When we normally justify a text, the browser is distributing the text according to the available space. If we stretch or reduce the viewport, we can see the text readjusting itself according to some obscure rule. The only certain thing is that white spaces between words increase or decrease according to the text flow.
With hyphens we can control all that.

Syntax
What we need to do is:
1) set the web page language (lang attribute);
2) choose the needed hyphens value (auto, manual, none).
Not very complicated:
p {
  -webkit-hyphens: manual;
  -moz-hyphens: manual;
  hyphens: manual;
}
With the above code, the text is hyphenated at the end of every paragraph, just in case we have a manual line break. This is the default value. Just to be more clear, as the W3C site states:
"Words are only hyphenated where there are characters inside the word that explicitly suggest hyphenation opportunities.[...] In HTML, ­ represents the soft hyphen character which suggests a hyphenation opportunity. "

If, instead of "manual", we set hyphens to "auto", every word at the end of the paragraph will be hyphenated, using the declared language.
"Words may be broken at appropriate hyphenation points either as determined by hyphenation characters inside the word or as determined automatically by a language-appropriate hyphenation resource. Conditional hyphenation characters inside a word, if present, take priority over automatic resources when determining hyphenation opportunities within the word." [W3C site]

Last, we can set hyphens to "none" just to be sure that no word will be hyphenated.

Compatibility
Just Safari 5.1+ and Firefox 6+ support hyphens. IE10 will probably support it with -ms prefix.
However we can still use hyphenator a js file which will "automatically hyphenate texts on websites". Check the web site (Google Code) if you really need to have a cross-browser compatibility.

Ok, that's all for today. Till next time...

0 thoughts:

Post a Comment

Comments are moderated. I apologize if I don't publish comments immediately.

However, I do answer to all the comments.