Frage

I will admit that I have a habit of using   between words when I don't want them to break (table headers for example).

Should I really style my element with white-space:nowrap? Are there any advantages/disadvantages to either if the only thing I am looking to do is keep words from wrapping?

War es hilfreich?

Lösung

There are cases where nonbreaking space cannot help:

  • the word contains a hyphen (e.g. web-developer);
  • hyphens: auto is used for the container element to do hyphenation automatically.

In these cases, white-space: nowrap is useful. Also, nonbreaking space works regardless of whether styles are applied to document while CSS rules solely work when styles are enabled.

Andere Tipps

white-space:nowrap has several advantages

  1. It can be applied globally to all matching text elements. If you put this in a class or apply it to all spans then you don't need to add/remove   in all files.
  2. It makes the html easier to read compared to having a bunch of html entities. It also allows your source code to be wrapped to the next line without messing anything up (a   at the end of a line renders as 2 spaces).
  3. It can be applied to elements that would be hard/impossible to replace the spaces with &nbsp;. For example in react <span style={{whiteSpace: 'nowrap'}}>{myValue}</span> works fine without needing to edit the value. This is especially useful for react since it will escape any html entities (and using a unicode non breaking space is very anti-human readable).
  4. It can be used for text that doesn't have spaces but has hyphens. white-space:nowrap also trumps hyphens: auto, overflow-wrap: anywhere, and word-break: break-word although you shouldn't have contradicting style.
  5. Whether or not to word wrap is within the scope of styling not document structure therefore white-space:nowrap is more proper than &nbsp; in the same way that CSS is preferred over <b>.
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top