I'm trying to create a loop where I apply different styling to each odd element. For this reason, using :nth-child(odd) would be great. However, for some reason that I don't understand, :nth-child(odd) gets applied to each element, not just the odd ones.
I created a codepen to showcase the issue.
h3.post-title a:nth-child(odd) {
font-weight: bold;
}
<div >
<div >
<a href="#">
<img src="#" alt="">
</a>
</div>
<div >
<a href="#"> </a>
<h3 >
<a href="#"></a>
</h3>
<span >
<i ></i>
</span>
</div>
</div>
<div >
<div >
<a href="#">
<img src="#" alt="">
</a>
</div>
<div >
<a href="#"> </a>
<h3 >
<a href="#">Title</a>
</h3>
<span >
<i ></i>
</span>
</div>
</div>
<div >
<div >
<a href="#">
<img src="#" alt="">
</a>
</div>
<div >
<a href="#"> </a>
<h3 >
<a href="#">Title</a>
</h3>
<span >
<i ></i>
</span>
</div>
</div>
<div >
<div >
<a href="#">
<img src="#" alt="">
</a>
</div>
<div >
<a href="#"> </a>
<h3 >
<a href="#">Title</a>
</h3>
<span >
<i ></i>
</span>
</div>
</div>
https://codepen.io/Pbalazs89/pen/eYjZNya
I tried selecting the elements directly (h3.post-title a:nth-child(odd) {}) and I tried selecting their parent container as well (.ts-grid-item-2 h3.post-title a:nth-child(odd) {}) The parent container is not present in the container, I just wanted to list what I tried.
CodePudding user response:
With your actual selector you target every a
inside you h3 title
.
You have to target every a
in the odd element container.
div.item:nth-child(odd) h3.post-title a {}
With this selector you target an a
element inside an h3
with class .post-title
inside any odd div with class .item
div.item:nth-child(odd) h3.post-title a {
font-weight: bold;
color:red;
}
<div >
<div >
<a href="#">
<img src="#" alt="">
</a>
</div>
<div >
<a href="#"> </a>
<h3 >
<a href="#"></a>
</h3>
<span >
<i ></i>
</span>
</div>
</div>
<div >
<div >
<a href="#">
<img src="#" alt="">
</a>
</div>
<div >
<a href="#"> </a>
<h3 >
<a href="#">Title</a>
</h3>
<span >
<i ></i>
</span>
</div>
</div>
<div >
<div >
<a href="#">
<img src="#" alt="">
</a>
</div>
<div >
<a href="#"> </a>
<h3 >
<a href="#">Title</a>
</h3>
<span >
<i ></i>
</span>
</div>
</div>
<div >
<div >
<a href="#">
<img src="#" alt="">
</a>
</div>
<div >
<a href="#"> </a>
<h3 >
<a href="#">Title</a>
</h3>
<span >
<i ></i>
</span>
</div>
</div>