我想在一个页面上的所有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;
}
(但显然这行不通)
当前回答
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,但如果你使用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开发更加动态。
SCSS+Compass使这变得简单,因为我们谈论的是预处理器。
#{headings(1,5)} {
//definitions
}
你可以在这里了解所有的Compass助手选择器:
使用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
不,在这种情况下,用逗号分隔的列表才是你想要的。
纯CSS
使用纯css有两种方法。这将针对页面内的所有标题元素(按要求)。
:is(h1, h2, h3, h4, h5, h6) {}
这一个做了同样的事情,但保持特异性为0。
:where(h1, h2, h3, h4, h5, h6) {}
与PostCSS
你也可以使用PostCSS和自定义选择器插件
@custom-selector :--headings h1, h2, h3, h4, h5, h6;
:--headings {
margin-top: 0;
}
输出:
h1,
h2,
h3,
h4,
h5,
h6 {
margin-top: 0;
}