css - 使用 CSS3 attr 函数在子项中使用父项的属性值

标签 css

我想设置一个 data-index父元素在其(嵌套)子元素之一上的值。预期结果:字符串“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

最佳答案

更新

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

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>



原版

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

以后,当attr()可以用于除 content 之外的属性,结合 css 变量,你可以这样做

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>

关于css - 使用 CSS3 attr 函数在子项中使用父项的属性值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42034739/

相关文章:

jquery - $(window).scroll() 循环,由于没有变量

css - 将 SVG 指定为背景图像并在 CSS 中设置 SVG 样式?

html - CSS,垂直对齐表格单元格中的 anchor

javascript - 更改 CSS "z-index"属性 : "Invalid left-hand side in assignment"

css - BootStrap的默认 anchor 标签样式如何传递

html - CSS:如何将边框分成两条线?

javascript - 为什么浏览器在加载网页资源时会暂停?

html - 无法居中 <li>

html - 控制div的高度

javascript - 使显示可见 : none with Javascript in Mobile View