Why do nth-of-type/nth-child selectors have no effect on nested elements?
P粉237689596
P粉237689596 2023-08-24 16:07:18
0
1
420

I'm trying to change the style of an odd number of divs nested within one div. For some reason, when nth-of-type(odd) is nested inside another div, it affects all divs. Here is my code for normal divs and an odd number of divs:

.video-entry-summary { width: 214px; height: 210px; margin-left: 10px; float: left; position: relative; overflow: hidden; border: 1px solid black; } .video-entry-summary:nth-of-type(odd) { width: 214px; height: 210px; margin-left: 0px; float: left; position: relative; overflow: hidden; border: 1px solid black; background: #ccc; }
video 1
video 2
video 3
video 4

For some reason, nth-of-type doesn't work when nested inside a div, but does work when they are not nested inside any div.

Working version when not nested within a div:

.video-entry-summary { width: 214px; height: 210px; margin-left: 10px; float: left; position: relative; overflow: hidden; border: 1px solid black; } .video-entry-summary:nth-of-type(odd) { width: 214px; height: 210px; margin-left: 0px; float: left; position: relative; overflow: hidden; border: 1px solid black; background: #ccc; }
video 1
video 2
video 3
video 4

How can I make the initial code the same as above?

P粉237689596
P粉237689596

reply all (1)
P粉497463473

:nth-of-type()is similar to:nth-child(), they must come from the same parent element. If you needdivfor these wrappers, use:nth-of-type()on these wrappers:

div.post:nth-of-type(odd) .video-entry-summary { width:214px; height:210px; margin-left:0px; float:left; position:relative; overflow:hidden; border:1px solid black; background:#ccc; }

If all sibling elements are.post, please use:nth-child()to avoid conflicts with:nth The true meaning of -of-type()Confusion:

.post:nth-child(odd) .video-entry-summary { width:214px; height:210px; margin-left:0px; float:left; position:relative; overflow:hidden; border:1px solid black; background:#ccc; }

.video-entry-summary { width: 214px; height: 210px; margin-left: 10px; float: left; position: relative; overflow: hidden; border: 1px solid black; } .post:nth-child(odd) .video-entry-summary { width: 214px; height: 210px; margin-left: 0px; float: left; position: relative; overflow: hidden; border: 1px solid black; background: #ccc; }
video 1
video 2
video 3
video 4
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!