Select second Child element inside Parent element using CSS

← Prev

You have a list of elements inside a parent element and you want to select the second element only, for some reason, using only CSS. How will do that? Its simple. You can use the CSS :nth-child selector to select a particular element or the nth element, inside its parent element.

Let us assume, I have a 3 different images, each inside a <p> element and all the <p>’s are inside a <div> (the parent element) and I want to change the style of 2nd element only.

<!DOCTYPE html>
<html>
<head>
<style>
    /* 	tranform (rotate) the 2nd element */
    .container > p:nth-child(2) {
        transform: rotate(20deg);
        -ms-transform: rotate(20deg);
        -webkit-transform: rotate(20deg);
        display: inline-block;
    }
    img {
        border: none;
        width: 75px;
    }
</style>
</head>
<body>
    <div class='container'>
        <p>
            <img src='../../images/theme/googlemaps.png'>
        </p>
        <!--         want to select and change style of this element only. -->
        <p>
            <img src='../../images/theme/javascript.png'>
        </p>
        <p>
            <img src='../../images/theme/sqlserver.png'>
        </p>
    </div>
</body>
</html>
Try it

Here, I am rotating the 2nd <p> element inside the parent element.

.container > p:nth-child(2) { … }

You have to mention the parent container along with the :nth-child selector. I have used the class name of the container. However, you can also use the container’s id.

Now, here’s another scenario. Along with an image inside the 2nd <p> element, I have another element, let’s say, a <span>, with a text. If I use the above example, it will rotate (or style) the span and the image. However, I want to select only the image, not the text. Here’s how I’ll do it.

.container > p:nth-child(2) img {
    transform: rotate(20deg);
    -ms-transform: rotate(20deg);
    -webkit-transform: rotate(20deg);
    display: inline-block;
}

I have added img after the :nth-child selector.

Point to Remember

Web designers often use in-line styles on various elements. The nth-child may not show you the desired result in such cases. You can over-ride the inline styles by using the !important property with the nth-child selector.

Let us assume, inside the <img> element you have defined border: none

<img src='../../images/theme/javascript.png' style='border: none;'>

and later you realized the image needs a border. Just do this…

.container > p:nth-child(2) img {
  border: solid 1px red!important;
}

That's it. Thanks for reading.

← Previous


Like this Article? Subscribe now, and get all the latest articles and tips, right in your inbox.
Delivered by FeedBurner