简体   繁体   中英

Is is possible to target last element inside a class div? CSS

I understand that I can target the last element if they are using the same class or they are the same element. But the way I am building is user will put in whatever element inside the (please see attached example). Just wondering is it still possible to call out by CSS? or that will be something cannot be done by CSS?

 .header p:last-of-type{ color: red; }
 <div class="header"> <h1>I am numbe one</h1> <h3>number two</h3> <p>something</p> <p>something</p> <button>last one - red</button> </div> <div class="header"> <h1>I am numbe one</h1> <h3>number two</h3> <p>last one - red</p> </div> <div class="header"> <p>number 1</p> <h1>something</h1> <h3>last one - red</h3> </div>

yes with last-child and .header p:last-child will target the last child if it's <p> </p> element and if you want to target the last element in a div that have a .header as a class.

you can use .header *:last-child as mention in the comments section by @Chris G

 .header *:last-child { color: red; }
 <div class="header"> <h1>I am numbe one</h1> <h3>number two</h3> <p>something</p> <p>something</p> <button>last one - red</button> </div> <div class="header"> <h1>I am numbe one</h1> <h3>number two</h3> <p>last one - red</p> </div> <div class="header"> <p>number 1</p> <h1>something</h1> <h3>last one - red</h3> <p>ddd</p> </div>

If you're trying to just add color: red; styling to the last <p> tag inside the last class='header' class, then you should use CSS Selectors :

CSS:

.header:last-of-type p:last-of-type {
    color: red;
}

You can check this working code sample .

Edit:

If you want to target the last element of each tag with the class='header' , you coud accomplish it like so:

CSS:

.header *:last-child {
  color: red;
}

Check the working code sample .

try this

 .header *:last-child{ color: red; }
 <div class="header"> <h1>I am numbe one</h1> <h3>number two</h3> <p>something</p> <p>something</p> <button>last one - red</button> </div> <div class="header"> <h1>I am numbe one</h1> <h3>number two</h3> <p>last one - red</p> </div> <div class="header"> <p>number 1</p> <h1>something</h1> <h3>last one - red</h3> </div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM