Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS data attribute new line character & pseudo-element content value

Is it possible to have a new line in a data attribute ?

I am trying to do something like this:

CSS:

[data-foo]:after {     content: attr(data-foo);     background-color: black; } 

HTML

<div data-foo="First line \a Second Line">foo</div> 

I found that "\a" is a new line in CSS, but still does not work for me.

like image 726
Snaker.Wood Avatar asked May 08 '13 22:05

Snaker.Wood


People also ask

How do I start a new line of content?

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.

How do I start a new line in HTML without br?

Use block-level elements to break the line without using <br> tag. There are many ways to break the line without using <br> tag. The used properties are listed below: white-space: pre; It is used to make elements acts like <pre> tag.


1 Answers

Here is how this can work. You need to modify your data attribute as follows:

[data-foo]:after {     content: attr(data-foo);     background-color: black;     color: white;     white-space: pre;     display: inline-block; }
<div data-foo='First line &#xa; Second Line'>foo</div>

Fiddle Demo: http://jsfiddle.net/audetwebdesign/cp4RF/

How It Works

Using \a does not work, but the equivalent HTML entity does, &#xa;.

According to the CSS2.1 spec, attr(attribute-label) returns a string but the string is not parsed by the CSS processor (I am not sure what this means exactly). I speculate that \a must be interpreted by the CSS processor in order for the code to be displayed property.

In contrast, the HTML entity is interpreted by the browser directly (I guess...) so it appears to work.

However, for the line feed to work, you need to set white-space: pre to preserve the white space in the pseudo-element. Note: you may also consider namely pre-wrap, or pre-line depending on the nature of your content.

Reference

Regarding getting the HTML entity code for a linefeed:
http://www.fileformat.info/info/unicode/char/000a/index.htm

Regarding the attr() value for the content property:
http://www.w3.org/TR/CSS2/generate.html#content

like image 138
Marc Audet Avatar answered Sep 18 '22 09:09

Marc Audet