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.

Share:
10,264
Bas
Author by

Bas

List item

Updated on June 02, 2022

Comments

  • Bas
    Bas almost 2 years

    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

  • Bas
    Bas almost 10 years
    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?
  • BoltClock
    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
    Bas almost 10 years
    ah okay, didnt know. Is it possible to insert a new line aswell?
  • BoltClock
    BoltClock almost 10 years
    @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
  • Bas
    Bas almost 10 years
    This didnt work for some reason: content: attr(class) '\A' attr(data-size);
  • BoltClock
    BoltClock almost 10 years
    Yeah I forgot to mention the bit about white-space. I've added a demo.
  • Paulie_D
    Paulie_D almost 10 years
    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/content