你可能不知道的CSS(6)-attr

原创
前端路迹
2024-8-14 08:34
编辑于 2024-8-14 08:43

对于 ::before 或 ::after 这种伪元素选择器,它有一个 content 属性,这个属性支持 attr 函数,而且大家可能不知道的是这个函数其实非常早就支持了,它的兼容性非常好,甚至兼容IE9。

attr() 函数可以从选择器对应的HTML元素的属性中提取值并将其插入到伪元素中,通过下面示例代码能更直观的了解它的作用。

<style>
    div {
        margin: 20px auto;
        height: 60px;
        width: 200px;
        background-color: #eee;
    }
    .div1::before {
        content: attr(class);
    }
    .div2::before {
        content: attr(data-t);
    }
    .div3::before {
        content: attr(xyz);
    }
</style>

<div class="div1">
</div>
<div class="div2" data-t="dattaset attr">
</div>
<div class="div3" xyz="custom attr">
</div>

效果

转载请注明出处。本文地址: https://www.qinshenxue.com/article/css-you-might-not-know-part-6.html
关注我的公众号