CodeinWP CodeinWP

The CSS white-space Property Explained

The CSS white-space PropertyCSS has a pretty useful property called white-space that I’m guessing goes unnoticed among CSS beginners. You can probably live without this property for quite some time, but once you learn how to use it, it will come in very handy and you’ll find yourself going back to it over and over again.

This article will attempt to describe, in a very practical, no-nonsense way, the different values for the CSS white-space property, and how each one can be used. I’ll do my best to avoid overly-technical jargon, but with this property, it’s not easy to explain without sounding overly-complex.

Some HTML Background

In (X)HTML, anytime you string together a bunch of spaces in your code, the actual page output in your browser will, by default, trim (or collapse) all those spaces down to a single space. This comes in handy, because it allows us to correctly indent and seperate the elements in our (X)HTML so it will be readable and maintainable — without creating extra unwanted space and line breaks in the browser output.

If you want to allow all space and line breaks to occur naturally, then you can use the big ugly cousin of the white-space property — the <pre> tag. All non-tag content inside of the <pre> tag will output virtually identically to what you have in the code. It will even cause a single line to push the boundaries of its parent if no explicit line breaks are used in the markup. So, while the default in HTML is to ignore multiple spaces and line breaks, you can override this using the <pre> tag.

(X)HTML also allows the use of the non-breaking space (&nbsp;). If you want to string together multiple spaces that you don’t want to collapse, you can use the non-breaking space. The older method of doing this involves using the <nobr> tag, but that tag is now deprecated, so it should not be used.

The white-space property is the cleaner CSS answer to the aforementioned (X)HTML methods of controlling white space.

Definition and Possible Values

Through a number of possible values, the white-space property gives us, via CSS, a way of defining how the browser handles multiple white space characters and line breaks. Of course, the portion of the document that you can target is limited to whatever can be targeted via CSS selectors.

Here are the different values for the white-space property, along with a visual demonstration of how each one works:

Value: normal

This is the default value. If it is set explicitly, it will have the same result as what naturally occurs in the output with no <pre> tags. As is the case with many CSS properties, the only time you would ever use the normal value is if you had already set one of the other values, and want to revert to the value “normal” for that element, or for a child element that inherits the unwanted value.

white-space: normal

Value: nowrap

This is the most commonly-used value for the white-space property, because it does exactly what the value normal does, except that it will not honor line breaks, and even natural line breaks that occur because of space limitations will also be suppressed.

An element that has its white-space property set to nowrap will not allow text or other inline elements to break naturally to the next line, but instead will push the boundaries of its parent until the line is completed, putting everything on a single line. This value will not affect strings of spaces between characters or inline elements, so multiple spaces will be collapsed to a single space, as usual.

white-space: nowrap

Value: pre

The value pre works exactly as you would expect: The same as content wrapped inside <pre> tags. All spaces and line breaks are honored, creating output in the browser that is virtually identical to what is in the markup. Also, just like the <pre> tag, if everything in the markup is on a single line, the line will push the boundaries of its parent to keep everything in the output on a single line.

white-space: pre

Value: pre-line

This value will work exactly the same way as the default (normal), except for one thing: Line breaks in the HTML will be honored. So, if you have multiple spaces between elements, those will be ignored as usual, but if in your markup you drop to a new line, the new line will also occur in the output. This value is not supported by Internet Explorer up to version 7, Firefox up to version 3.0, and Opera up to version 9.2.

white-space: pre-line

Value: pre-wrap

This value is exactly the same as pre, except that it will naturally wrap lines according to the boundaries of its parent. So it will not force everything on a single line to imitate what’s in the markup, but it will honor multiple spaces and explicit line breaks. This value is not supported by Internet Explorer up to version 7, and Firefox up to version 3.0.

white-space: pre-wrap

A Few Common Uses

Probably the most common reason to use the white-space property is when applying it to a link that you don’t want to drop to the next line. Look at the screen capture below from the zaBox “confirm details” page:

zaBox

The “read more” link has the &raquo; (») character next to it, but because there wasn’t enough room, it dropped to the next line. This would have been avoided if the link had its white-space property set to nowrap. The link would then naturally fall to the next line as a single unit, and wouldn’t be broken up. This point helps emphasize the fact that the white-space property only affects the content inside the element to which it’s applied. So, while the link itself will drop to the next line, the text inside the link will not be separated via line breaks.

<

p>Another use for this property is when you want to prevent a row of inline boxes from wrapping to the next line. I mentioned this in a previous article discussing how to center multiple block-level elements on a single line.

Misconceptions

One possible problem for beginners using this property (as I already alluded to above) is that they assume that setting whitespace: nowrap on an element will prevent that element from dropping to the next line if it is part of a group of floated boxes. The white-space property, however, will only apply to the inline elements inside of the element it’s applied to, and will not affect block elements or the spacing of the element itself.

As mentioned, you’ll most often use this property when you set it to the value nowrap, since that particular value has some practical use. Since the values pre-line and pre-wrap don’t work with Internet Explorer, they will not likely be used very often, but they do seem to offer practical value if they become more widely supported.

Please offer comments on other possible uses, or on problems that can occur with the white-space property. I’m sure it has numerous practical benefits and potential drawbacks that I haven’t mentioned here.

104 Responses

  1. Hitesh Chavda says:

    To the point article.
    Thanks man.

  2. Armin C. says:

    Awesome article, I have to admit I haven’t payed this property much attention (didn’t bother to see any real use), until now. Thank you.

  3. AHHP says:

    Thank you a lot.
    It was very useful for me…

  4. Jogos Gratis says:

    Interesting article! Even though I’ve never used this property, it can come handy when dealing with multiple divs where I need to avoid wraps.

    • Just remember that it won’t work on elements that are still “block-level”. The elements have to be “inline” or “inline-block”.

      • Jogos Gratis says:

        Do you mean that if I have two parallels divs using the property “float:left” I can’t use the property “white-space” to avoid wrapping?

        • Dillon Es says:

          No you can’t.

          This is meant to wrap things like text (inline elements)

          Your best bet if you are using a fixed width layout is to define the widths of the divs too so that they fit in like a puzzle!

  5. petar says:

    thanks for the explanation – the examples made it crystal clear!

  6. emarilyn says:

    Thanks! I’ve never paid much attention to this property either . . . going to try this on some of my current sites.

  7. Janko says:

    Great read, Louis. white-space is quite handy when styling code samples (if you don’t use code formatters, and personally I don’t like them.)

  8. crazy, I feel I am fairly well versed in CSS, didn’t even know about this property, will be using, thanks!

  9. Great article! Thought I’m using this property for a while, I’ve never heard before of the two last values.

    There’s also this usefull hack using the white-space property, to center multiple divs in a single line: http://www.impressivewebs.com/center-multiple-divs

  10. Zaigham says:

    Thanks for detailed insight! :)

  11. flashmac says:

    Nice article, education on all fronts. Well presented too. Thanks IW

  12. Clear explanation, nice article!

  13. Paulo Gonçalves says:

    Thanks man!
    Very useful indeed.

  14. Atul says:

    Thanks for the useful tips. I will start using it from my next project

  15. CSS-Blog says:

    Very nice and helpful article, long live white-space!

  16. Mateus says:

    Nice article!
    Wish i’ve read this before.

  17. Indeed this was very useful. I also like very much the simple design of your blog. Great work.

    • Well, I’ve been using this simple layout for most posts now, and it seems to have gone over very well.

      The rest of the site still has the old layout, but I think I’m going to do everything in this style from now on. Thanks.

  18. Lauren says:

    Eye-opener!!

    This solves a common problem I encounter with some headlines that have an awkward text flow or widow. I always feel weird about adding a .

    Thanks!!

  19. Bali says:

    Nice article :)

  20. Frederick says:

    Great read, I do forget to use this tag sometimes ;)

  21. Very focused article, very well written.

  22. Scott Corgan says:

    Whitespace, MySpace, Office Space. This topic is over “explained”…

  23. bractus says:

    Nice article,
    I prefer to use pre vs. code tag for code samples.

  24. The tag you used in this article for white-spacing is new for me and i learn from it.

  25. tyafolabi says:

    Great article. I haven’t bothered to know what white-space is, or its use, until now. This article is an eye opener for wannabe designers like me. Also I love your blog. Beautifully Simple. A ton of thanks.

  26. electric_g says:

    There are two errors in the pre-wrap image: the look like of the example must have “spaces and a line break” on a new line, and the explanation (“explicit line breaks are ignored”) is wrong, while the one above (“it will honor multiple spaces and explicit line breaks”) is correct.

    • Great eye! Thanks for pointing that out, I’ve corrected it. It’s amazing how many times you can review something, but still make a mistake like that. Shows the importance of getting a neutral eye on things.

      Those last two properties were actually new to me too when I did the research, so I think I was still slightly confused. Although I did have the text explanation correct outside of the graphic, so who knows.

      It should all be correct now, thank you.

      • electric_g says:

        Now the word “spaces” must be on the second line ;)
        I think the example would be better to understand showing a natural line break too, perhaps you could present the same sentence with two different font-size.

        • *facepalm*

          Thanks, man, I’ll have to fix it later because I have no access right now.

        • Fixed. And yes, you’re right, showing the natural line break would be better. But I think the text explanation is enough, especially considering that property will probably rarely be used.

          Thanks again for spotting those errors.

      • Golden Lee says:

        Absolutle the best for this subject, detailed yet concise and to the point!

  27. This is a great article. Using CSS for the past 4/5 years i have to admit i have never used the white-space property. Now that i know what it is and how to use it, i think it will be very useful for me.

    Thanks for sharing.

  28. Megha says:

    Very helpful article.

    Thanks for providing useful information.Very well xplained.

  29. joelk says:

    thanks
    i got to this site via smashing mag.

    I’m a css geek (or so i think) and never had to use the white-space property.

  30. matt says:

    very nice! I can’t wait until CSS3 is supported everywhere…

  31. Alitimate says:

    Nice Article. Really didnt think white spaces can get really this important.

  32. Congratulation, very useful article!

  33. I guess ya learn something new every day. The pre-wrap setting looks great for replacing nbsp.

  34. Sahus Pilwal says:

    I’m sure this would have helped in previous sites I have worked on. I’ll certainly think about the usage of CSS element white-space in the future! Thanks for the informative post! ;)

  35. silvercover says:

    Thanks for this valuable illustrated article.

  36. Hello,

    Thank you for the article, it is well written and easy to understand.
    I’ve only been using CSS for about a year and a half, so maybe this is a silly question, but in some cases couldn’t you just use a break tag, or is that less efficient?

    • Yes, you would, but the white-space property is good for when you don’t want a break to occur within a certain portion of text (using “nowrap” as the value), but you don’t want it to occur before that section of text.

      See the example in the article from Zabox. In that case, if the paragraph is shorter, the link will stay on the same line as the last line of the paragraph, whereas if the pargagraph is too long (as is the case in the example), then the entire link will drop to the next line and won’t break in an awkward spot.

      If you use the break tag, then you’re forcing the break when you may not need it at all. This, of course, would only apply to dynamically-generated content where you don’t know if the paragraph is long or short.

  37. Sander says:

    This is great! Been looking for a method for stopping links in a horizontal menu to break-up a while back. Found this post through SmashingMagazine, so now I know :) Thank you very much!

    Sander

  38. memo says:

    Nice article about white space.
    Lessons learned.

  39. Kevin says:

    Nice article. Definitely sending noobs here, because it can be an exceptionally useful tool in defining layouts.

  40. Baljeet says:

    really gr8 lesson to learn.. thanks buddy..
    i will now start using this tag also.. :)

  41. João Pereira says:

    Excelente article. Thanks for sharing.

  42. Isabelle says:

    nice! i love learning new things like that!

  43. Ilie Ciorba says:

    Most of us don’t pay enough attention to such details, even if those small details make our design stand out!

  44. Nick Pyett says:

    I think there is still an argument for using tags (to cater for users without CSS and in RSS feeds). Also, I’ve used the link technique you mention on my own site – and its a life saver!

    Great stuff

  45. I stumbled upon this article by accident and it just happened to solve a issue I’ve been trying to fix.

    Thanks!

  46. Dan says:

    Thanks! This will save
    so much time!

  47. Farhan says:

    We want to break words in a table cell into lines. “white-space:pre-line” did trick for us. Unfortunately, ONLY IE 8 supports”pre-line”. I already checked “word-wrap: break-word;” but this does not seems to be working. Even my editor doesn’t recognize “word-wrap: break-word;” as a valid CSS. Any help on how to accomplish this.
    Regards,

  48. Arron Davies says:

    Great read! will be keeping this in mind for the future.

  49. JD Hobbs says:

    I had that very same issue happen to me just yesterday on a “Read More >” link for a WordPress blog….length of the excerpt was pushing the arrow to the next line.

    How lucky I am to stumble upon this article the very next day! Gone back and fixed now.

    Cheers!

  50. kcmr says:

    Great post.
    I usually use this property to simulate min-width for buttons (A tags) in IE 6: http://uninstallme.com/enlaces-con-un-ancho-minimo-en-internet-explorer-6/ (in spanish).
    It’s also usefull to simulate the nowrap attribute for table cells aplying it to a SPAN element:

    <td><span class="nowrap">bla bla bla</span></td>

  51. csssample says:

    Excellent Article, Keep posting like this

  52. salvaxp1 says:

    Very nice explanation man.. Do Not know ’bout this ’till now.. and to think that I was thinking I now to much already,…
    silly me LOL

    thanks to U Now I know that I Do know just a little.. maybe not a thing hahaha
    best regards.

  53. Andy Kinsey says:

    Fantastic article and something I’ve known for a while but not really used, i will look to use it now! thanks

  54. Arnold says:

    Good and informative. Thanks!

  55. justin bryan says:

    Great help! i used this tag when i was working on page http://www.txtimpact.com/shared-shortcode.asp . you can view these features easily. thanks again.

  56. You gave nice ideas here. I done a research on the issue and learnt most peoples will agree with your blog.Thanks a lot for enjoying this beauty article with me. I am appreciating it very much! Looking forward to another great article. Good luck to the author! all the best!

  57. Elomelo says:

    hey thanks for this idea. i fixed my site http://doridro.com with that. hats off :)

  58. thanks for sharing. great news

  59. Really great! Thanks

  60. Geoffrey Hom says:

    That was very helpful. Thank you so much.

  61. Thanks,I am a Chinese,it is my first comment in English website.

  62. Roy Barber says:

    Im learning something new everyday from these archives! fantastic post. Ive never used the white space property in any of my designs, tbh i never knew it existed! silly me!

  63. khan says:

    Thats awesome .. been making websites for 3 years now and did not give that much attention to these properties.

    Cheers Mate

  64. Karen says:

    Thank you for this article. Whitespace is something I have ignored in the past, but will make use of in the future

  65. Moncler says:

    Thank you for this article. Whitespace is something I have ignored in the past

  66. derljhun says:

    Thank you for this article. Whitespace is something I have ignored in the past, but will make use of in the future

  67. Jahoorulla Shaik says:

    Thanks a lot. Awesome article…

  68. dattathri says:

    Thanks for useful stuff……actually i want to break the sentance after 50 character, how can i use that in word wrap…….

    thanks in advance

  69. Mya says:

    Well said. Understood it perfectly. Thanks.

  70. Zach says:

    I’m a HTML and computer idiot, yet I’ve been tasked to make updates to our Online Help page. I’m getting a “white space” line break but it doesn’t seem evident within the HTML code, only when you are viewing the page. Here is the code:
    b)   Enter
    the <Correct Month> in the RE Due Month text
    box.
    c)   Click
    the Save and Return button.

    • You’d have to show me the actual page. It could be “pre” tags or maybe the white=space property set to “pre” or something like that. Again, I can’t help you unless see a real page. Can you send a link and explain which section you’re referring to?

  71. Travis says:

    I will start using white space more, I was using other methods, but the white space property makes more sense. Thanks for the info.

  72. MAT says:

    You switched the results of pre-line and pre-wrap. I just tried in Google Chrome, and pre-wrap does what I wanted, it does word wrap, but does not stretch the word to fit the width, while pre-line does pretty much like normal, wraps the text and stretches the sentence to fill the width in first line before wrapping to second and so on.

    Thanks for the info, I was looking for feature such as pre-wrap ;)

    Actually, nowrap would work the best for me, but for some reason, in my case it stretches that invisible box rather than just not displaying extra text, and also moves the sentence start to the left for a couple of pixels.

  73. Tulsi says:

    Really nice…

  74. noyasahar says:

    I really never heard of this property before. I’m a programmer familiar with c++, c#, ajax, php with 3 years of experience but never heard of this css property.

  75. GorillaKing says:

    Thanks man! Save me a bunch of times! ;)

  76. Thulasi says:

    Thanks for nice article.i have one query.In my project there is an JSP page where option called”Edit section” underlined.
    When it the code got migrated to IE11,the Underline is coming long and extending beyond the text.i went back and search the source code in IE11 and found 7 &nbsp; appending to the text which is causing so much of space and underline is coming as long.But in my original code &nbsp; is not appended.
    Could you please suggest how can i modify code to remove the long underline.Thanks in advance.

    • You’ll just have to modify the code and remove those. I can’t really help you with that if I don’t have access to the code, so I don’t know what you’re able to do.

      If it’s something that you can’t modify, then maybe you can inject some JavaScript into the page to remove the unwanted characters.

  77. Sunil Rana says:

    Thanks for clearing my blunder confusion. its really a awesome clarification.

  78. Prasanth says:

    I have a html page which has multiple links(inside anchor tags) present in it. Whenever the links are too long/at end of a line it will span to multiple lines. Issue is when clicking on the link on the first line the whole anchor tag content shifts to the bottom line. Because of which user have to click the link multiple times to reach the “href”. Please suggest a solution or this.

  79. Philippe V says:

    Google Chrome and Safari still do not honor this property correctly.

    The following snippet:

    <span style="white-space:nowrap">Some text <i>(other text)</i> :

    will still allow a line-break to occur before the internal inline element or after it (i.e. before the opening parenthese and after the closing one), because the outer span (supposed to be unbreakable) contains in fact 3 elements.

    This is a problem when formatting lists of items horizontally because the separator between items is frequently in an inline element separated from the inline element that just precedes it (usually with a ” ” text element between them supposed to be unbreakable.

    <span style="white-space:nowrap"><bdi>item1</bdi> |</span> <bdi>item2</bdi> |</span> <span style="white-space:nowrap"><bd>item3</bdi></span>

    Such horizontal list of items will still allow the vertical bar to wrap to the next line without the item with which it should remain attached this becomes a nightmare with list of items containing some necessary inline formattings, such as containing images/icons, or some subelements formatted in italics or bold, or containing links: those items may be broken in the middle unexpectedly.

    This is clearly a bug of Chrome/Safari/Webkit which honors this property only within the same inner text element, but not all inner inline elements.

  80. Petar Ozretic says:

    Ty so much, very helpful :D

  81. Great article! We always send our trainee designers here for a small CSS white-space old school lesson. Thanks for sharing.

Leave a Reply

Comment Rules: Please use a real name or alias. Keywords are not allowed in the "name" field and deep URLs are not allowed in the "Website" field. If you use keywords or deep URLs, your comment or URL will be removed. No foul language, please. Thank you for cooperating.

Markdown in use! Use `backticks` for inline code snippets and triple backticks at start and end for code blocks. You can also indent a code block four spaces. And no need to escape HTML, just type it correctly but make sure it's inside code delimeters (backticks or triple backticks).