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

岁酱吖の 提交于 2019-11-27 03:55:50

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

You can use a plain line break inside an attribute value:

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

Browsers have been buggy in this respect, and the HTML specifications have not been quite clear on this; they discuss the meaning of line breaks in element content (where they are taking as equivalent to spaces), but not in attribute values. In HTML5 CR, the parsing rules for attribute values make it clear that line breaks are simply added to the attribute value. Modern browsers generally play by such rules.

However, when you use the value in CSS via attr(...), the line break will normally be treated as equivalent to a space, so you need to set white-space on the pseudo-element to a value that makes line breaks honored, namely pre, pre-wrap, or pre-line.

P.S. In HTML, the notation \a is just two data characters, with no special meaning. The notation &#xa; would denote a line break (specifically, LINE FEED), but it would be just equivalent to an actual line break in souce.

...and if you're trying to figure this out and happen to be using HAML and AngularJS then use \n.

%a.tooltip{:"data-tip" => "Cost Per Unit: {{humanized_cost}} \n(Calculated for applicable Feature Qty.) "}

results in:

Cost Per Unit: $10.54
(Calculated for applicable Feature Qty.)

Okay, Here is one easy way to do this. you should write it as

data-foo='First line </br> Second Line'

and instead of using .text(), you can use .html(). when you use .html() then it will take as line break and this should solve your problem.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!