Let Me Tink About It
Let Me Tink About It

Reputation: 16132

CSS: How to select elements by referencing the parent, not the child

Let's say I have several <p> elements inside a <div> like this:

HTML
<div>
  <p></p>
  <p></p>
  <p></p> <!-- I want to select the "last" element, <p> or not <p> -->
</div>

Now, say I want to style the last element, <p> or not <p>. One way to do that is to use the last-child selector on the <p>'s like this:

CSS
<style>
  p:last-child {
    /* Awesome styles go here */
  }
</style>

Question

How do I style the last element (<p> or not <p>) by referencing <div> but NOT <p>?

Live Code Example

p:last-child {
  color: red;
  font-weight: bold
}
<div>
  <p>Foo</p>
  <p>Bar</p>
  <p>Baz</p> <!-- I want to select the "last" element, <p> or not <p> -->
</div>

Upvotes: 2

Views: 81

Answers (1)

Yeldar Kurmangaliyev
Yeldar Kurmangaliyev

Reputation: 34244

You can use > in your selector to describe direct children:

div > p:last-child {
}

This CSS will affect only the p tags which are the last child of div tag.

If, for some reason, you don't want to reference p at all, you can use * selector:

div > *:last-child {
}

It will affect the last child of the div whatever it is.

For example:

div > *:last-child {
  font-weight: bold;
  color: red;
}
<div>
  <p>1</p>
  <p>2</p>
  <p>3</p>    
</div>

<div>
  <a href="#">1</a>
  <a href="#">2</a>
  <a href="#">3</a>    
</div>

<div>
  <span>1</span>
  <i>2</i>
  <i>3</i> 
</div>

Upvotes: 4

Related Questions