CSS Trick: nth-of-type()

2019-05-07 09:51发布

问题:

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> 

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

EG: if div-x rendered are 4 then apply pseudo-element to 3rd div-x else dont

I tried below but it applies to all odd element

&:nth-of-type(odd) {
  border-bottom: none;
}

Any hint/help will be appreciated Thanks !

回答1:

You could use :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;
}

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 divs). I used two declarations merely for the sake of readability.

Check out this demo.

However, ensure that support of the pseudo-class is sufficient for your requirements. This page (2013) states:

: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.

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  │
└────────┴─────────────────┴───────────────────┴───────┴────────┘

And for mobile browsers:

┌─────────┬────────────────────────┬───────────┬──────────────┬───────────────┐
│ Android │ Firefox Mobile (Gecko) │ IE Mobile │ Opera Mobile │ Safari Mobile │
├─────────┼────────────────────────┼───────────┼──────────────┼───────────────┤
│   2.1   │       1.0 (1.9.1)      │    9.0    │     10.0     │      3.2      │
└─────────┴────────────────────────┴───────────┴──────────────┴───────────────┘