Multiple content: attr() values
10,264
To concatenate two or more string values in CSS, separate them with whitespace:
.element:before {
content: attr(class) ' ' attr(data-size);
}
Note that the whitespace between the attr()
functions and the quotes is not the same as the whitespace within the quotes. The latter is an actual string containing a space character, which will separate the two attribute values in the output. The whitespace between the three parts is the operator that joins them together.
Comments
-
Bas almost 2 years
I'm trying to display 2 things in my elements; the
class
name and an own createddata-size
variable. Seperated with one white space.I could get this working by doing this:
.element:before { content: attr(class); } .element:after { content: attr(data-size); }
But it doesnt seem like a the right way to do it. I have also tried to do this:
.element:before { content: attr(class data-size); }
But that didnt work aswell.
Input
HTML
<div class="element" data-size="20"></div>
CSS
.element:before { content: attr(class data-size); }
Wanted output
element 20
-
Bas almost 10 yearsThank you, accepting your answer when i can. Can i do this as many times as i want and can i put other things in here aswell?
-
BoltClock almost 10 years@Bas: Yes, you can do this with as many strings as you want. You can also place any other string you want as long as you put it in quotes, for example
content: attr(data-foo) ' abc';
-
Bas almost 10 yearsah okay, didnt know. Is it possible to insert a new line aswell?
-
BoltClock almost 10 years@Bas: Yes, to insert a newline use
'\A'
. You will need to addwhite-space: pre
orpre-wrap
to your rule in order to get it to actually render a line break. Here's a demo: jsfiddle.net/BoltClock/vD4E3/9 -
Bas almost 10 yearsThis didnt work for some reason:
content: attr(class) '\A' attr(data-size);
-
BoltClock almost 10 yearsYeah I forgot to mention the bit about
white-space
. I've added a demo. -
Paulie_D almost 10 yearsIt should also be mentioned strongly that the properly is not meant to display actual content. It's supposed to be used for styling in conjunction with pseudo-elements - developer.mozilla.org/en-US/docs/Web/CSS/content