125

Is it possible to use newline character in CSS content property to force a line break? Something like:

figcaption:before
{
    content: 'Figure \n' + attr(title);
}
||||||
  • 2
    Does this answer help? stackoverflow.com/a/4609491/582278 – Dan Blows Jan 30 '12 at 11:22
  • @Blowski, yeah, but it doesn't work in my fiddle – Saeed Neamati Jan 30 '12 at 11:28
  • @SaeedNeamati does in mine. What browser are you looking in? – Dan Blows Jan 30 '12 at 11:31
  • 5
    Now it works. The last fiddle – Saeed Neamati Jan 30 '12 at 11:32
  • This question is not a duplicate of the question indicated. That one asks how to create a break before starting the generated content, which can be done using display, clear etc. This question asks how to put newlines/line-breaks within the generated content, which is what I want, and that can't be accomplished the same way. – Stephen P Aug 19 '15 at 23:29
138

The content property accepts a string and:

A string cannot directly contain a newline. To include a newline in a string, use an escape representing the line feed character in ISO-10646 (U+000A), such as "\A" or "\00000a". This character represents the generic notion of "newline" in CSS.

(No idea about actual browser support.)

You can check Using character escapes in markup and CSS for reference about the escape syntax, which essentially is:

  • \20AC must be followed by a space if the next character is one of a-f, A-F, 0-9
  • \0020AC must be 6 digits long, no space needed (but can be included)

NOTE: use \00000a rather than just \A when escaping an arbitrary string, because if the newline is followed by a number or any character from [a-f] range, this may give an undesired result.

||||||
  • 36
    Note that newline characters inserted this way are treated like any other newlines in an HTML document: they'll be rendered as a regular space character by browsers by default, and only as regular newlines in preformatted content. – BoltClock Jan 30 '12 at 11:26
  • It doesn't work. jsfiddel. – Saeed Neamati Jan 30 '12 at 11:27
  • 8
    @SaeedNeamati - It does: jsfiddle.net/q4WC4/1 – Álvaro González Jan 30 '12 at 11:29
  • 16
    Then you should also include white-space property, yeah? Am I right? – Saeed Neamati Jan 30 '12 at 11:31
  • 6
    @SaeedNeamati - The key is on @BoltClock's comment. Playing with white-space is just a simple way to make line feeds visible. – Álvaro González Jan 30 '12 at 11:44
143
figcaption:before
{
    content: 'Figure \a' attr(title);
    white-space: pre;
}

Note that in the content attribute value, concatenation is expressed just by whitespace, not by a “+” sign. The escape notation \a in a CSS string literal indicates a linebreak character.

||||||

Not the answer you're looking for? Browse other questions tagged or ask your own question.