Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
187 views
in Technique[技术] by (71.8m points)

html - 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

<div data-foo='First line &#xa; Second Line'>foo</div>

and the CSS (proof of concept):

[data-foo]:after {
    content: attr(data-foo);
    background-color: black;
    color: white;
    white-space: pre;
    display: inline-block;
}

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...