20

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

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
Bas
  • 2,106
  • 5
  • 21
  • 59

1 Answers1

39

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.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
  • 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 Jun 26 '14 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 Jun 26 '14 at 10:24
  • ah okay, didnt know. Is it possible to insert a new line aswell? – Bas Jun 26 '14 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: http://jsfiddle.net/BoltClock/vD4E3/9 – BoltClock Jun 26 '14 at 10:27
  • 1
    This didnt work for some reason: `content: attr(class) '\A' attr(data-size);` – Bas Jun 26 '14 at 10:28
  • Yeah I forgot to mention the bit about `white-space`. I've added a demo. – BoltClock Jun 26 '14 at 10:29
  • 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 - https://developer.mozilla.org/en-US/docs/Web/CSS/content – Paulie_D Jun 26 '14 at 10:47