我想在一个页面上的所有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;
}

(但显然这行不通)


当前回答

手写笔的选择插值

for n in 1..6
  h{n}
    font: 32px/42px trajan-pro-1,trajan-pro-2;

其他回答

不,在这种情况下,用逗号分隔的列表才是你想要的。

它不是基本的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开发更加动态。

如果你正在使用SASS,你也可以使用这个mixin:

@mixin headings {
    h1, h2, h3,
    h4, h5, h6 {
        @content;
    }
}

像这样使用它:

@include headings {
    font: 32px/42px trajan-pro-1, trajan-pro-2;
}

编辑:我个人最喜欢的方法是在每个标题元素上扩展一个占位符选择器。

h1, h2, h3,
h4, h5, h6 {
    @extend %headings !optional;
}

然后我可以瞄准所有的标题,就像我瞄准任何单个类一样,例如:

.element > %headings {
    color: red;
}

新的:is() CSS伪类可以在一个选择器中完成。

例如,下面是如何瞄准容器元素中的所有标题:

.container :is(h1, h2, h3, h4, h5, h6)
{
    color: red;
}

大多数浏览器现在都支持:is(),但请记住,大多数在2020年之前制作的浏览器都不支持没有前缀的它,所以如果你需要支持旧浏览器,请谨慎使用这个前缀。

在某些情况下,您可能希望使用:where()伪类,它与:is()非常相似,但具有不同的专一性规则。

SCSS+Compass使这变得简单,因为我们谈论的是预处理器。

#{headings(1,5)} {
    //definitions
  }

你可以在这里了解所有的Compass助手选择器: