使用CSS3 attr函数在子级中使用父级的属性值 [英] using attribute value of a parent in a child using CSS3 attr function

查看:34
本文介绍了使用CSS3 attr函数在子级中使用父级的属性值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在其(嵌套的)子元素之一上设置父元素的 data-index 值.所需的结果:字符串"index"应该出现在 h2.heading 周围.

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.

标记:

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

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

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

推荐答案

更新

一种解决方法是直接在html元素上设置CSS变量并使用它.

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>

原始

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

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

将来,当 attr()可以用于除 content 之外的属性时,结合CSS变量,您可以像这样

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>

这篇关于使用CSS3 attr函数在子级中使用父级的属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆