CSS Trick:nth-of-type() [英] CSS Trick: nth-of-type()
问题描述
您好我正在寻找特定的东西,甚至不确定是否可以使用纯CSS:
Hi I am looking to something particular and not even sure if it can be done using pure CSS:
<div-1>
<div-x></div-x>
<div-x></div-x>
<div-x></div-x>
<div-x></div-x>
<div-1>
我在scss中尝试做的是
What I am trying to do in scss is
if <div-x> render count is even
then only apply &:last-child{ something; } to div number len(<div-x>)-1
end
strong> EG:
如果div-x渲染为4,则将伪元素应用于第三个div-x else dont
EG: if div-x rendered are 4 then apply pseudo-element to 3rd div-x else dont
它适用于所有奇数元素
&:nth-of-type(odd) {
border-bottom: none;
}
任何提示/帮助将感谢! b
Any hint/help will be appreciated Thanks !
推荐答案
您可以使用:nth-last-of-type
:
.wrapper div:nth-of-type(even) + div:nth-last-of-type(2) {
background-color: #ADD8E6;
}
/* for when there are only two occurrences of this element type */
.wrapper div:nth-last-of-type(2):first-of-type {
background-color: #ADD8E6;
}
第一个选择器将为倒数第二个 div
仅当紧接着出现偶然的
s)。我使用两个声明只是为了可读性。 div
。第二个选择器是当它也是倒数第二个 div
时(当只有两个<$时),对第一个 div
c $ c> div
The first selector will style the penultimate div
only if it is immediately preceded by an even occurrence of div
. The second selector is to style the first div
when it is also the penultimate div
(when there are only two div
s). I used two declarations merely for the sake of readability.
查看 this demo。
但是,请确保伪类的支持足以满足您的要求。 此页(2013年) :
However, ensure that support of the pseudo-class is sufficient for your requirements. This page (2013) states:
:nth-last-of-type
3,这意味着旧版本的浏览器不支持它。然而,现代浏览器支持是无可挑剔的,新的伪选择器广泛应用于生产环境。如果您需要较旧的浏览器支持,请使用polyfill for IE,或者以非关键方式使用这些选择器,这是建议的。
:nth-last-of-type
was introduced in CSS Selectors Module 3, which means old versions of browsers do not support it. However, modern browser support is impeccable, and the new pseudo-selectors are widely used in production environments. If you require older browser support, either polyfill for IE, or use these selectors in non-critical ways á la progressive enhancement, which is recommended.
这 MDN页面指出以下浏览器具有给定版本的基本支持:
This MDN page states the following browsers have "basic support" as of the given versions:
┌────────┬─────────────────┬───────────────────┬───────┬────────┐
│ Chrome │ Firefox (Gecko) │ Internet Explorer │ Opera │ Safari │
├────────┼─────────────────┼───────────────────┼───────┼────────┤
│ 4.0 │ 3.5 (1.9.1) │ 9.0 │ 9.5 │ 3.2 │
└────────┴─────────────────┴───────────────────┴───────┴────────┘
对于移动浏览器:
┌─────────┬────────────────────────┬───────────┬──────────────┬───────────────┐
│ Android │ Firefox Mobile (Gecko) │ IE Mobile │ Opera Mobile │ Safari Mobile │
├─────────┼────────────────────────┼───────────┼──────────────┼───────────────┤
│ 2.1 │ 1.0 (1.9.1) │ 9.0 │ 10.0 │ 3.2 │
└─────────┴────────────────────────┴───────────┴──────────────┴───────────────┘
这篇关于CSS Trick:nth-of-type()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!