我想在一个页面上的所有h标签。我知道你可以这样做……
h1,
h2,
h3,
h4,
h5,
h6 {
font: 32px/42px trajan-pro-1,trajan-pro-2;
}
但是是否有更有效的方法来使用先进的CSS选择器?例如:
[att^=h] {
font: 32px/42px trajan-pro-1,trajan-pro-2;
}
(但显然这行不通)
我想在一个页面上的所有h标签。我知道你可以这样做……
h1,
h2,
h3,
h4,
h5,
h6 {
font: 32px/42px trajan-pro-1,trajan-pro-2;
}
但是是否有更有效的方法来使用先进的CSS选择器?例如:
[att^=h] {
font: 32px/42px trajan-pro-1,trajan-pro-2;
}
(但显然这行不通)
当前回答
使用scss可以循环6,并使用逗号分隔符将空变量$heading附加
$headings: ();
@for $index from 1 through 6 {
$headings: list.append($headings, h#{$index}, $separator: comma);
}
#{$headings} {
--default: var(--dark);
color: var(--default);
}
由于@steve
其他回答
SCSS+Compass使这变得简单,因为我们谈论的是预处理器。
#{headings(1,5)} {
//definitions
}
你可以在这里了解所有的Compass助手选择器:
它不是基本的css,但如果你使用LESS (http://lesscss.org),你可以使用递归来做到这一点:
.hClass (@index) when (@index > 0) {
h@{index} {
font: 32px/42px trajan-pro-1,trajan-pro-2;
}
.hClass(@index - 1);
}
.hClass(6);
Sass (http://sass-lang.com)将允许您管理这个,但不允许递归;下面这些实例有@for语法:
@for $index from 1 through 6 {
h#{$index}{
font: 32px/42px trajan-pro-1,trajan-pro-2;
}
}
如果你使用的不是像LESS或Sass这样编译成CSS的动态语言,你绝对应该看看这些选项中的一个。它们可以真正简化并使您的CSS开发更加动态。
新的:is() CSS伪类可以在一个选择器中完成。
例如,下面是如何瞄准容器元素中的所有标题:
.container :is(h1, h2, h3, h4, h5, h6)
{
color: red;
}
大多数浏览器现在都支持:is(),但请记住,大多数在2020年之前制作的浏览器都不支持没有前缀的它,所以如果你需要支持旧浏览器,请谨慎使用这个前缀。
在某些情况下,您可能希望使用:where()伪类,它与:is()非常相似,但具有不同的专一性规则。
jQuery的所有h标签(h1, h2等)的选择器是“:header”。例如,如果你想用jQuery把所有的h标签都变成红色,可以使用:
(头”中写道:“美元). css(“颜色”、“红”)
不,在这种情况下,用逗号分隔的列表才是你想要的。