我正在嘗試更改 div 內的奇數 div 的樣式。由於某種原因,當 nth-of-type(odd)
位於另一個 div 內時,它會影響我的所有 div。這是我的常規 div 和奇數 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; }
<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>
出於某種原因,nth-of-type
在包裹在我的 div 內時不起作用,但在它們未包裹在任何 div 內時卻起作用。
未包裹在 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; }
<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>
如何使初始程式碼與上面的程式碼一樣運作?
:nth-of-type()
與:nth-child()
類似,因為它們必須都來自同一個父級。如果您需要這些包裝器div
,請在這些包裝器上使用:nth-of-type()
:如果所有同級都是
.post
,請使用:nth-child()
以避免與:nth- of-type()
的真正意義: