Joao Alves Marrucho Joao Alves Marrucho - 1 month ago 12
CSS Question

Last-child not working with classes. Last-of-type also not working

I am trying to select the :last-child of a series of wordpress posts (with the same class) in my style.css file.
Here is a simplified version of my document structure:

<div id="container">
<div id="content">
<!--start .post-->
<div id="post-33" class="hentry p1 post">
<h2 class="entry-title"><a href="url">Post 1</a></h2>
<div class="entry-content">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>
</div>
<!--end .post -->
<!--start .post-->
<div id="post-24" class="hentry p1 post">
<h2 class="entry-title"><a href="url">Post 2</a></h2>
<div class="entry-content">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>
</div>
<!--end .post -->
<!--start .post-->
<div id="post-24" class="hentry p1 post">
<h2 class="entry-title"><a href="url">Post 3</a></h2>
<div class="entry-content">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.</p>
</div>
</div>
<!--end .post -->

<div id="nav-below" class="navigation">
<div class="nav-previous"></div>
<div class="nav-next"></div>
</div>
</div><!-- #content -->
</div><!-- #container -->


I have tried this and although it works fine with the :first-child selector it does not work at all with the :last-child.

.post .entry-content {
background-color: pink;
border-bottom: 2px solid;
}

.post:first-child .entry-content {
background-color: red;
border-bottom: 0px solid;
}

.post:last-child .entry-content {
background-color: yellow;
border-bottom: 0px solid;
}


Any thoughts?
Here is the live version of my site: http://dev.visualvisual.com/

Answer

Use nth-of-type and nth-last-of-type.

.post:nth-of-type(1) .entry-content { 
    background-color: red; 
    border-bottom: 0px solid;
}

.post:nth-last-of-type(2) .entry-content { 
    background-color: yellow; 
    border-bottom: 0px solid;
}

first-child and last-child, are, like the name suggests, for operating on children, so you'd want to use #content:last-child to find last element (not necessarily .post though).

Codepen