為什麼在嵌套元素上,nth-of-type/nth-child選擇器無效?
P粉237689596
2023-08-24 16:07:18
<p>我正在嘗試更改嵌套在一個div內的奇數個div的樣式。由於某些原因,當<code>nth-of-type(odd)</code>嵌套在另一個div內時,它會影響到所有的div。以下是我對普通div和奇數個div的程式碼:</p>
<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>
<p>由於某種原因,當嵌套在div內時,<code>nth-of-type</code>不起作用,但是當它們不嵌套在任何div內時起作用。 </p>
<p><strong>不嵌套在div內時的工作版本:</strong></p>
<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>
<p>如何讓初始程式碼與上述程式碼相同? </p>
:nth-of-type()
和:nth-child()
類似,它們都必須來自同一個父元素。如果你需要這些包裝的div
,請在這些包裝上使用:nth-of-type()
:如果所有的兄弟元素都是
.post
,請使用:nth-child()
來避免與:nth -of-type()
的真正意義混淆: