我想在一个页面上的所有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;
}
(但显然这行不通)
当前回答
纯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;
}
其他回答
手写笔的选择插值
for n in 1..6
h{n}
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
使用纯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;
}
如果你想用一个选择器对文档中的所有标题进行分类,如下所示:
<h1 class="heading">...heading text...</h1>
<h2 class="heading">...heading text...</h2>
在CSS中
.heading{
color: #Dad;
background-color: #DadDad;
}
我并不是说这总是最佳实践,但它可能是有用的,对于目标语法来说,在许多方面都更容易,
所以如果你给所有h1到h6在html中相同的。heading类,那么你可以修改他们的任何html文档,利用css表。
好处是,与“section div article h1, etc{}”相比,更多的全局控制,
缺点,而不是在css中调用所有的选择器,你将在html中有更多的输入,但我发现,在html中有一个类的目标所有标题可以是有益的,只是要小心在css的优先级,因为冲突可能会产生
它不是基本的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开发更加动态。