Home > Enterprise >  Is there a way using Only CSS to display the value of an attribute as html and text on a page?
Is there a way using Only CSS to display the value of an attribute as html and text on a page?

Time:10-07

If I have this html:

<ul>
<li attr="Hi Bob">Boring Text</li>
</ul>

Can I display "Hi Bob" as an element using only CSS?

Hi Bob o Boring Text

As an aside, is it possible to add the value of this attribute using only CSS to a separate element before the element the attribute is in?

CodePudding user response:

It is possible with the HTML5 data-* attribute.

li:before {
  content: attr(data-attr) " o ";
}
<ul>
  <li data-attr="Hi Bob">Boring Text</li>
</ul>

Simply add an attribute to your HTML tag with the prefix data- (e.g.: data-test). Now you're able to access this attribute in CSS with the attr() function (e.g.: attr(data-test)).

CodePudding user response:

You can use the attr as content on a pseudo before element - but be aware that though the user can see the text it isn't actually in an element in the DOM so it probably won't be read out by screen readers - i.e. it's not a good way if that text is important rather than just a nice embellishment.

If you want to place it far from the actual element you could position it, but this snippet just puts it immediately before with an added space:

ul li[attr]::before {
  content: attr(attr) ' ';
}
<ul>
  <li attr="Hi Bob">Boring Text</li>
</ul>

Note: although browsers will pick up any attribute name - in this case 'attr' - the standard for non-standard attributes, i.e. ones you have created yourself, is to start them with data-.

  • Related