呼吁 ::nth-everything

Avatar of Chris Coyier
Chris Coyier

DigitalOcean 为您旅程的每个阶段提供云产品。立即开始使用 200 美元的免费额度!

使用 CSS3,我们拥有位置伪类选择器,可以帮助我们在没有其他区分特征的情况下选择特定元素,而这些元素仅仅是在 DOM 中相对于其兄弟元素的位置。

:first-child
:last-child
:nth-child
:nth-last-child

:first-of-type
:last-of-type
:nth-of-type
:nth-last-of-type

:only-child
:only-of-type

我们还获得了一些特定于文本的伪元素,以帮助满足我们的排版需求。

::first-letter
::first-line

这是一个很好的开始,但如果我们能够将整个“:nth”的概念扩展到这些排版选择器,那将非常有用。让我来说服你。

请注意,下面的大多数代码都是无效的。这是示例代码。“如果可以就好了”之类的代码。

::nth-line() / ::last-line / ::nth-last-line()

我们已经有了::first-line,所以为了完整起见,让我们添加::nth-line()::last-line::nth-last-line()

有了这些,我们可以选择一首诗的前两行来突出显示。

article.poem p:first-child::nth-line(-n+2) {
  font-variant-caps: small-caps;
  color: red;
}
我不懂诗歌,Brendon。

或者我们可以淡出段落的结尾。

article.poem p:last-child::nth-last-line(3) {
   color: hsla(26, 5%, 25%, 1);
   font-size: 70%;
}
article.poem p:last-child::nth-last-line(2) {
   color: hsla(26, 5%, 50%, 1);
   font-size: 60%;
}
article.poem p:last-child::nth-last-line(1) {
   color: hsla(26, 5%, 75%, 1);
   font-size: 50%
}

如果允许我们在这些行伪元素上使用生成内容,我们可以实现类似于行号的功能,而无需诉诸于侵入性标记。

pre::nth-line(n)::before {
  content: counter(line) ". ";
  color: #999;
}
看,妈妈,简单的实用多行代码样式。

Adam Prescott 的相关文章。

::nth-word() / ::first-word / ::last-word / ::nth-last-word()

我们目前没有任何基于单词的伪元素。不过我们有word-spacing,这值得注意。

一个用例类似于使用::first-letter进行首字母大写,只是对整个单词进行操作。

article p::first-word {
  float: left;
  font-size: 300%;
  margin: 0 10px 10px 0;
}

与上面“淡出”行类似,我们可以使用::nth-last-word(n)逐个单词淡出段落。

::nth-letter() / ::last-letter() / ::nth-last-letter()

我们已经有了::first-letter,它得到了相当不错的使用,那么为什么不将其完整化呢?

在所有这些“新”选择器中,::nth-letter可能是最有用的。例如,Lettering.js 为我们用包装字母,以便我们可以选择单个字母。使用::nth-letter,这将完全没有必要。

请看这个例子

h1.fancy::nth-letter(n) {
  display: inline-block;
  padding: 20px 10px;
}
h1.fancy::nth-letter(odd) {
  transform: skewY(15deg);
  background: url(light-red-pattern.png);
}
h1.fancy::nth-letter(even) {
  transform: skewY(-15deg);
  background: url(dark-red-pattern.png);
}
h1.fancy::nth-word(n) {
  margin-right: 20px;
}
h1.fancy::last-word {
  margin-right: 0;
}

查看Lettering.js上的所有示例——所有这些都是对这一需求的良好示例。

另一个单词/字母组合示例是正式的“信件”,例如

Dear Emily,

yadda yadda yadda.

Love, Chris.

也许这封“信件”是由数据库中的动态内容生成的,但我们希望确保开头和结尾行的正确大小写和样式。

.letter p:first-child::nth-word(-n+2)::nth-letter(1),
.letter p:last-child:nth-word(-n+2):nth-letter(1) {
  text-transform: uppercase;
}

完整集合

因此,如果我们得到所有这些,完整集合将是

:first-child        :first-of-type        :only-child
:last-child         :last-of-type         :only-of-type                  
:nth-child          :nth-of-type    
:nth-last-child     :nth-last-of-type

::first-letter      ::first-line          ::first-word
::last-letter       ::last-line           ::last-word
::nth-letter        ::nth-line            ::nth-word
::nth-last-letter   ::nth-last-line       ::nth-last-word 

再次强调,这只是美好的愿望。如果有人可以让我在他们面前展示这一点并对此做些什么,我会的。我还会根据收到的反馈(正面或负面)更新此内容。

作为记录,这不是一个新的请求。Anne van Kesteren 在 2003 年就呼吁过。