2

I'd like to use the ::before pseudoelement to insert some text that is found in another area of the HTML file.

My HTML:

<html>
    <body notetext="Note">
     ...
    <p class="bodytext">Don't press the red button!</p>
    </body>

I can use content:attr to select an attribute of the current element, but is it possible to refer to an attribute of an ancestor element? Like you can in XPath, for example (//body/@notetext)

the non-working CSS I have:

p.bodytext::before {
    content:attr(notetext);
}

I'm using Antennahouse Formatter, for CSS Paged Media.

Hobbes
  • 1,964
  • 3
  • 18
  • 35

3 Answers3

5

If you can alter the HTML you may consider the use of CSS variables like this:

p.bodytext::before {
  content: var(--text);
}
<body style="--text:'Note '">

  <p class="bodytext">Don't press the red button!</p>
</body>
Temani Afif
  • 245,468
  • 26
  • 309
  • 415
  • I'm sure he is trying to bind an attribute of some element, to the content of another, not the styling. – Rainbow May 08 '18 at 12:42
  • @ZohirSalakCeNa and that's whay I did using another alternative – Temani Afif May 08 '18 at 12:44
  • No, i mean like in WPF, bind a control attribute that keep changing to another, maybe display it somewhere. – Rainbow May 08 '18 at 12:47
  • Interesting approach. Unfortunately my processor (Antennahouse Formatter, for CSS Paged Media) won't let met use variables. – Hobbes May 08 '18 at 12:52
1

With css only it is not possible to refer to another elements content. It is also not possible to refer to a parent element. I would advise you to use javascript and data attributes to solve your problem.

Temani Afif's answer is great an i would recommend it as long as you don't need to support Internet Explorer. Otherwise you would need a css custom properties IE polyfill.

Der Alex
  • 718
  • 3
  • 16
0

Antenna House (https://www.antennahouse.com/) Formatter has an -ah-attr-from() extension function (https://www.antenna.co.jp/AHF/help/en/ahf-ext.html#attr-from).

The function prototype is as for attr() but with the addition of a parameter specifying the ancestor element:

-ah-attr-from( <from-name> , <attr-name> <type-or-unit>? [ , <fallback> ]? )
Tony Graham
  • 7,306
  • 13
  • 20
  • 1
    most likely nobody knows what is "AH Formatter" and the link is also dead.. this isn't valid CSS code. This should not be the selected answer – vsync Jul 01 '23 at 13:21
  • The question states "I'm using Antennahouse Formatter, for CSS Paged Media.", and the question has the 'antenna-house' tag. The link has been updated. – Tony Graham Jul 04 '23 at 16:54