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

1
  • try attr(class)" "attr(data-size)
    – King King
    Commented Jun 26, 2014 at 10:20

1 Answer 1

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.

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?
    – Bas
    Commented Jun 26, 2014 at 10:24
  • 1
    @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';
    – BoltClock
    Commented Jun 26, 2014 at 10:24
  • ah okay, didnt know. Is it possible to insert a new line aswell?
    – Bas
    Commented Jun 26, 2014 at 10:25
  • 3
    @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/9
    – BoltClock
    Commented Jun 26, 2014 at 10:27
  • 1
    This didnt work for some reason: content: attr(class) '\A' attr(data-size);
    – Bas
    Commented Jun 26, 2014 at 10:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.