Multiple content: attr() values
Asked Answered
A

1

21

I'm trying to display 2 things in my elements; the class name and an own created data-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

Demo here

Alegre answered 26/6, 2014 at 10:19 Comment(1)
try attr(class)" "attr(data-size)Fortier
T
41

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.

Tremulous answered 26/6, 2014 at 10:22 Comment(7)
Thank 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?Alegre
@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';Tremulous
ah okay, didnt know. Is it possible to insert a new line aswell?Alegre
@Bas: Yes, to insert a newline use '\A'. You will need to add white-space: pre or pre-wrap to your rule in order to get it to actually render a line break. Here's a demo: jsfiddle.net/BoltClock/vD4E3/9Tremulous
This didnt work for some reason: content: attr(class) '\A' attr(data-size);Alegre
Yeah I forgot to mention the bit about white-space. I've added a demo.Tremulous
It 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/contentImmunogenic

© 2022 - 2024 — McMap. All rights reserved.