Issue
I am building a website with PHP and MySQL which contains articles, and each of those articles can contain comments (rather like a typical blog). Each article page is like this
<?php
$blog_id = "1";
include("../includes/blog.php");
?>
and all the code is in blog.php.
The intention is that the comments on each page should have alternating background colours to make it clear when one comment finishes and another begins. I am using this CSS to achieve it
.comment:nth-child(2n+1){background-color:rgba(0,0,0,0.075)}
So it is my understanding that the first, third, etc comments should be light grey while second, fourth, etc will have a white background.
The first article I created has one comment at the bottom and it is grey as expected. The second article also has one comment but that has a white background. Using the code inspector in Chrome shows that it is not picking up the "nth-child" line of CSS. When I temporarily added a second dummy comment it had a grey background, so it seems to be applying to even elements instead of odd ones.
I have read the many similar questions on here but none of them got me to a solution. I have tried nth-child(odd) instead of nth-child(2n+1) but it made no difference. I even tried wrapping all the comments in another div and using this CSS instead, but that really messed things up by applying itself to nested paras within the comments.
.comment-wrapper :nth-child(2n+1){background-color:rgba(0,0,0,0.075)}
Any practical suggestions would be so appreciated. Thanks.
Solution
The nth-child pseudo selector actually acts on the child, not the parent.
This CSS selector looks for an element with class .comment that is an odd child:
.comment:nth-child(2n+1)
.comment:nth-child(2n+1) {
color: red;
}
<div class="comment">
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
</div>
<div class="comment">
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
</div>
This CSS selector looks for an odd direct child of an element with class .comment:
.comment > :nth-child(2n+1)
.comment > :nth-child(2n+1) {
color: red;
}
<div class="comment">
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
</div>
<div class="comment">
<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
</div>
Your new rule would look something like this:
.comment > :nth-child(2n+1) {
background-color: rgba(0,0,0,0.075);
}
The reason for the > direct child combinator instead of just a space (descendant combinator) is so that we don't target nested elements inside the comments like you mentioned happened to you in one of your other attempts.
I recommend using odd in your selector for readability and the using the new CSS color syntax:
.comment > :nth-child(odd) {
background-color: rgb(0 0 0 / 0.075);
}
Answered By - Zach Jensz
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.