Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using attribute value of a parent in a child using CSS3 attr function

Tags:

css

I want to set a data-index value of a parent element on one of its (nested) children. Desired result: string "index" should appear around the h2.heading.

Markup:

<div class="foo" data-index="index">
    <div>
        <h2 class="heading"><span>title</span></h2>
    </div>
</div>

CSS (the first data-index rule works - but not in the right place):

div.foo[data-index] .heading span {
    display: none;
}

div.foo[data-index]::after { 
    content: attr(data-index);
    color: green;
}

div.foo[data-index] .heading::after { 
    content: attr(data-index);
    color: red;
    border: 1px solid red;
}

http://codepen.io/anon/pen/jyxdoz

like image 953
montrealist Avatar asked Feb 03 '17 23:02

montrealist


1 Answers

update

A workaround could be to set a CSS variable directly on the html element and use that.

div.foo[data-index] .heading span {
    display: none;
}

div.foo[data-index] .heading::after { 
    content: var(--index);
    color: red;
    border: 1px solid red;
}
<div class="foo" style="--index:'test';" data-index>
  <div>
    <h2 class="heading"><span>title</span></h2>
  </div>
</div>

original

It can't be done currently (as mentioned the attr only works on the current element).

In the future, when attr() can be used to properties besides the content, combined with css variables you could do it like this

div.foo[data-index] .heading span {
  display: none;
}
div.foo[data-index] {
  --data: attr(data-index);
  --index: var(--data);
}
div.foo[data-index] .heading::after {
  content: var(--index);
  color: red;
  border: 1px solid red;
}
<div class="foo" data-index="index">
  <div>
    <h2 class="heading"><span>title</span></h2>
  </div>
</div>
like image 102
Gabriele Petrioli Avatar answered Sep 19 '22 09:09

Gabriele Petrioli