Newline character sequence in CSS 'content' property?

Css

Css Problem Overview


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);
}

Css Solutions


Solution 1 - Css

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.

Solution 2 - Css

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.

The tricky bit is to remember that HTML collapses white-space by default.

figure {
    /* Avoid whitespace collapse to illustrate what works and what doesn't */
    white-space: pre-wrap;
}

#first figcaption:before
{
    /* \n is not a valid entity in this context */
    content: 'Figure \n Chemistry';
    display: block;  
}

#second figcaption:before
{
    content: 'Figure \A Chemistry';
    display: block;  
}

<figure id='first'>
    <figcaption>Experiments</figcaption>
</figure>

<figure id='second'>
    <figcaption>Experiments</figcaption>
</figure>

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSaeed NeamatiView Question on Stackoverflow
Solution 1 - CssJukka K. KorpelaView Answer on Stackoverflow
Solution 2 - CssÁlvaro GonzálezView Answer on Stackoverflow