简体   繁体   English

是否可以定位 class div 中的最后一个元素? CSS

[英]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.我知道如果它们使用相同的 class 或者它们是相同的元素,我可以定位最后一个元素。 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?只是想知道 CSS 是否仍然可以调用? or that will be something cannot be done by CSS?或者那将是 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.是的,使用last-child.header p:last-child将定位最后一个子元素,如果它是<p> </p>元素,并且如果您想将.header作为 ZA42F2ED4F8EB4CAB6 的 div 中的最后一个元素作为目标

you can use .header *:last-child as mention in the comments section by @Chris G您可以使用.header *:last-child@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;如果您只想添加color: red; styling to the last <p> tag inside the last class='header' class, then you should use CSS Selectors :将样式设置为最后一个class='header' class 中的最后一个<p>标记,那么您应该使用CSS 选择器

CSS: 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:如果你想使用class='header'来定位每个标签的最后一个元素,你可以像这样完成它:

CSS: 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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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