使用CSS3 attr函数使用子节点中父节点的属性值

时间:2017-02-03 23:40:56

标签: css css3

我想在其中一个(嵌套)子元素上设置父元素的data-index值。期望的结果:字符串"索引"应出现在h2.heading附近。

标记:

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

CSS(第一个data-index规则有效 - 但不在正确的位置):

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

2 个答案:

答案 0 :(得分:5)

<强>更新

解决方法可能是直接在html元素上设置CSS变量并使用它。

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

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

<强>原始

目前无法完成(如上所述attr仅适用于当前元素)。

将来,当attr()可以用于content以外的属性时,结合css变量就可以这样做

&#13;
&#13;
div.foo[data-index] .heading span {
  display: none;
}
div.foo[data-index] {
  --index: attr(data-index);
}
div.foo[data-index] .heading::after {
  content: var(--index);
  color: red;
  border: 1px solid red;
}
&#13;
<div class="foo" data-index="index">
  <div>
    <h2 class="heading"><span>title</span></h2>
  </div>
</div>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

你可以使用这个css。

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

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

请注意使用:before伪元素。

我认为这就是你要找的东西。