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

(但显然这行不通)


当前回答

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

其他回答

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

2022年7月更新

未来来了,:is选择器就是你要找的东西,正如@silverwind在2020年给出的答案中所描述的那样(现在是选定的答案)。

原来的答案

要用香草CSS解决这个问题,请在h1..编辑元素:

<section class="row">
  <header>
    <h1>AMD RX Series</h1>
    <small>These come in different brands and types</small>
  </header>
</header>

<div class="row">
  <h3>Sapphire RX460 OC 2/4GB</h3>
  <small>Available in 2GB and 4GB models</small>
</div>

如果你能发现模式,你就可以写一个选择器来瞄准你想要的东西。给定上面的例子,所有h1..h6元素可以通过组合来自CSS3的:first-child和:not伪类来作为目标,在所有现代浏览器中都可以使用,如下所示:

.row :first-child:not(header) { /* ... */ }

在未来,高级伪类选择器,如:has()和随后的兄弟组合符(~),将随着Web标准的不断发展而提供更多的控制。

以下是我仅用(现代)CSS来解决这个问题的尝试。

背景:在Joplin(非常好的笔记应用程序,链接),有一个userfile.css,你可以写你的自定义CSS显示和导出的标记笔记。

我想把所有的标题直接放在(相邻的兄弟姐妹)某些标签之后,即p, ul, ol和nav,在两者之间添加一个边距。因此:

p + h1,
p + h2,
p + h3,
p + h4,
p + h5,
p + h6,
ul + h1,
ul + h2,
ul + h3,
ul + h4,
ul + h5,
ul + h6,
ol + h1,
ol + h2,
ol + h3,
ol + h4,
ol + h5,
ol + h6,
nav + h1,
nav + h2,
nav + h3,
nav + h4,
nav + h5,
nav + h6  {
  margin-top: 2em;
}

哇。很长时间。这样的选择器。

于是我来到这里,学习,尝试:

p   + :is(h1, h2, h3, h4, h5, h6),
ul  + :is(h1, h2, h3, h4, h5, h6),
ol  + :is(h1, h2, h3, h4, h5, h6),
nav + :is(h1, h2, h3, h4, h5, h6) {
  margin-top: 2em;
}

嗯。短得多。好了。

然后,我突然想到:

:is(p, ul, ol, nav) + :is(h1, h2, h3, h4, h5, h6) {
  margin-top: 2em;
}

耶,这个也有用!怎么amazoomble !

这也可以使用:where()或其他CSS组合符,如~甚至(space)来创建CSS选择器的“矩阵”,而不是非常长的列表。

credit:本页上所有引用:is()选择器的答案。

它不是基本的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;
}