Why are nth-of-type/nth-child selectors invalid on nested elements?
P粉662802882
2023-08-24 14:50:42
<p>I'm trying to change the style of an odd number of divs contained within one div. But the style selector <code>nth-of-type(odd)</code> for odd-numbered divs will affect all divs when included in another div. Here is my code for a normal div and an odd number of divs: </p>
<p><br /></p>
<pre class="brush:css;toolbar:false;">.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;
}</pre>
<pre class="brush:html;toolbar:false;"><div id="post-501" class="post-501 post type-post status-publish format-standard hentry category-moto-dz- films tag-news-sub-2">
<div class="video-entry-summary">
video 1
</div>
</div>
<div id="post-240" class="post-240 post type-post status-publish format-standard hentry category-videos">
<div class="video-entry-summary">
video 2
</div>
</div>
<div id="post-232" class="post-232 post type-post status-publish format-standard hentry category-videos">
<div class="video-entry-summary">
video 3
</div>
</div>
<div id="post-223" class="post-223 post type-post status-publish format-standard hentry category-videos">
<div class="video-entry-summary">
video 4
</div>
</div></pre>
<p><br /></p>
<p>For some reason, the <code>nth-of-type</code> selectors don't work when included in my div, but they work when they are not included in any div. </p>
<p><strong>Working version when not enclosed in a div: </strong></p>
<p><br /></p>
<pre class="brush:css;toolbar:false;">.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;
}</pre>
<pre class="brush:html;toolbar:false;"><div class="video-entry-summary">
video 1
</div>
<div class="video-entry-summary">
video 2
</div>
<div class="video-entry-summary">
video 3
</div>
<div class="video-entry-summary">
video 4
</div></pre>
<p><br /></p>
<p>How can I make the initial code the same as above? </p>
on these wrappers:nth-of-type()
is similar to:nth-child()
, they must come from the same parent element. If you need these wrappeddiv
, you should use:nth-of-type()
:If all sibling elements are
.post
, you should use:nth-child()
to avoid conflicts with: The true meaning of nth-of-type()
Confusion: