Is there a way to group nth-child CSS rules for the same parent

I have the following CSS rules:

 #div .item62 > .wrap > .cont > .level1 > div:nth-child(9),
 #div .item62 > .wrap > .cont > .level1 > div:nth-child(11),
 #div .item62 > .wrap > .cont > .level1 > div:nth-child(n+12){
    width: 140px ;
 }

      

I would like to group these rules to make the code shorter and probably make the code more efficient when the parent is selected once (these rules force the browser engine to search three times for the same "parent" or is this already optimized ?).

Is there a way to write these rules shorter?

Since the code structure is generated by third party code, I cannot add a separate class or change the HTML structure.

I have not been able to find a CSS method that would allow a single parent with multiple different children to be selected without rewriting the entire child path. Also I don't have additional CSS preprocessors.

+3


source to share


3 answers


Your current CSS rule is the shortest you can write without a preprocessor.



+2


source


The expression :nth-child(n+12)

matches every child starting with and :nth-child(12)

. Assuming 11

both n+12

are not typos, you can condense them with a single expression n+11

:

#div .item62 > .wrap > .cont > .level1 > div:nth-child(9),
#div .item62 > .wrap > .cont > .level1 > div:nth-child(n+11)

      

Note that :nth-child(9), :nth-child(n+11)

essentially the same as :nth-child(n+9)

, that is, everything from and including :nth-child(9)

but excluding :nth-child(10)

.



With that in mind, you can rewrite the above list of selectors with :not(:nth-child(10))

:

#div .item62 > .wrap > .cont > .level1 > div:nth-child(n+9):not(:nth-child(10))

      

You now have one complex negated selector. I can't comment on the performance implications of negating in the mix, however, unless profiling shows that this selector is causing significant performance issues, I would argue that it is absolutely worth it to cut the selector list by more than half bytes. Personally, I can't imagine what :not(:nth-child(10))

would be much cheaper or much more expensive than :nth-child(n+b)

any non-zero one b

. Each of them is a rather complex operation.

+1


source


You can do something like this, it won't be much shorter and technically redundant.

#div > .item62 > .wrap > .cont > .level1 > div:nth-child(2n+9),
#div > .item62 > .wrap > .cont > .level1 > div:nth-child(n+12)
{
  width:140px;
}

      

0


source







All Articles