Focusing on the final item within a group of different elements using CSS

After experimenting with different approaches, I attempted the following;

@mixin text-format{
>p, >ul, >h1, >h2, >h3, >h4, >h5{
    &:last-of-type{
        background-color:green;
    }
}
}

.text-body{
@include text-format;
}

Using Pure CSS

.text-body > p:last-of-type, .text-body > ul:last-of-type, .text-body > h1:last-of-type, .text-body > h2:last-of-type, .text-body > h3:last-of-type, .text-body > h4:last-of-type, .text-body > h5:last-of-type {
  background-color: green;
}

My intention was to target the last element within the div regardless of its type, but only within the specified element types in the selector.

For a visualization, check out the Fiddle provided below; http://jsfiddle.net/bazzle/bcLt62jx/

Answer №1

It seems like you're in search of

.text-body > :nth-last-child(1 of p, ul, h1, h2, h3, h4, h5)

mentioned in the Selectors 4 specification (initially introduced as :nth-last-match()). This selector narrows down possible matches to specific element types and selects the last occurrence of those within the parent element, .text-body. Here is an example:

<div class="text-body">
  <h1></h1>
  <p></p>
  <ul></ul>
  <h2></h2>
  <p></p>
  <span></span>
</div>

In this scenario, there are six children, five of which belong to any of p, ul, h1, h2, h3, h4, h5. The last element from these five is the p preceding the span, therefore fulfilling the given selector. The h1 would match a similar expression with :nth-child(), while the span will never satisfy such criteria based on the selector-list — in fact, the span can be represented as :not(p, ul, h1, h2, h3, h4, h5).

Although :nth-child(), :nth-last-child(), and :not() were introduced in Selectors 3, the selector-list argument is a novelty in Selectors 4. However, no implementation currently exists for it, leaving its availability uncertain. Unfortunately, there is no equivalent alternative with current tools since it's fundamentally comparable to this question, except instead of a class selector, it targets the nth (last) child matching a group of options. Both scenarios involve working with the nth occurrence of a subset of an element's children.

You could resort to using JavaScript to, for instance, assign a class to the final instance among these element types during page load. A native DOM/Selectors APIs approach would look like this:

var types = document.querySelectorAll('.text-body > p, .text-body > ul, .text-body > h1, .text-body > h2, .text-body > h3, .text-body > h4, .text-body > h5');
types[types.length - 1].className += ' last';

... which might seem complex compared to the following jQuery solution:

$('.text-body').children('p, ul, h1, h2, h3, h4, h5').last().addClass('last');

Remember that

:nth-last-child(1 of p, ul, h1, h2, h3, h4, h5)

is not equal to

:last-child:matches(p, ul, h1, h2, h3, h4, h5)

as the latter only applies if the last child of its parent belongs to any of those specified element types. Essentially, :last-child:matches(...) corresponds to

p, ul... { &:last-child { ... } }
(referring to Harry's response).

Answer №2

If you want to target the last child within a parent element regardless of its element type, you can achieve this by using the simple :last-child selector as shown below:

& > :last-child{
  background-color:green;
}

This selector will style the last child within the .text-body class without considering the element type.

In the following code snippet, you can observe how the background-color: green is applied to the last child of both .text-body blocks, even though the last child in the first block is a p and in the second block is a span.

.text-body p,
.text-body ul {
  margin-bottom: 1em;
}
.text-body >:last-child {
  background-color: green;
}
<div class="text-body">
  <h1>Title</h1>
  <p>
    But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born...
  </p>
  <ul>
    <li>List item 1</li>
    <li>List item 2</li>
    <li>List item 3</li>
    <li>List item 4</li>
  </ul>
</div>

<div class="text-body">
  <h1>Title</h1>
  <p>
    But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born...
  </p>
  <ul>
    <li>List item 1</li>
    <li>List item 2</li>
    <li>List item 3</li>
    <li>List item 4</li>
  </ul>
  <h2>Subtitle</h2>
  <p>
    Nor again is there anyone who loves or pursues or desires to obtain pain...
  </p>
</div>


On the other hand, if you only want to select the last child when its element type matches a specific list of values, you can use the last-child selector with additional criteria like below:

>p, >ul, >h1, >h2, >h3, >h4, >h5{
    &:last-child{
        background-color:green;
    }
}

This selector will style the last child if its element type is among p, ul, h1, h2, h3, h4, h5.

If the element type of the last child does not match these values, the style won't be applied. In the provided code snippet, you can see how the background-color: green is only applied to the last child of the first .text-body block but not to the second one where the last child is a span.

.text-body p,
.text-body ul {
  margin-bottom: 1em;
}
.text-body > p:last-child,
.text-body > ul:last-child,
.text-body > h1:last-child,
.text-body > h2:last-child,
.text-body > h3:last-child,
.text-body > h4:last-child,
.text-body > h5:last-child {
  background-color: green;
}
<div class="text-body">
  <h1>Title</h1>
  <p>
    But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born...
  </p>
  <ul>
    <li>List item 1</li>
    <li>List item 2</li>
    <li>List item 3</li>
    <li>List item 4</li>
  </ul>
  <h2>Subtitle</h2>
  <p>
    Nor again is there anyone who loves or pursues or desires to obtain pain...
  </p>
</div>

<div class="text-body">
  <h1>Title</h1>
  <p>
    But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born...
  </p>
  <ul>
    <li>List item 1</li>
    <li>List item 2</li>
    <li>List item 3</li>
    <li>List item 4</li>
  </ul>
  <h2>Subtitle</h2>
  <span>
    Nor again is there anyone who loves or pursues or desires to obtain pain...
  </span>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieve content from the pushState state object

$(function(){ $('button').click(function(e){ e.preventDefault(); var nextUrl = 'page1.html'; var previousUrl = window.location.href; $.get(nextUrl, function(data){ $('body').ht ...

Having trouble with jQuery's scrollLeft function on elements that are not currently visible

Within a large container DIV that contains numerous other elements and has a scroll bar, an issue arises when determining the value of scrollLeft. When the DIV is visible, the scrollLeft() function returns the correct value, but when the element is hidden, ...

directive scope is not functioning

Looking to incorporate an input element into my Google Map, I've written the code below: app.directive('GooglePlaceAutoComplete', function() { return { restrict:'AEC', replace: true, scope: { myMap:&ap ...

What are some ways to prevent Bootstrap cards with images from stretching too far and creating additional white space?

My bootstrap cards are stretching too tall when I include images. Is there a way to prevent this overextension? https://i.sstatic.net/HEaYh.png https://i.sstatic.net/21DVq.png ...

Center the ordered list using margin:auto

Does anyone know how to properly set margin-auto on an ordered list? I'm having trouble with it in a complex setup. Unfortunately, I can't create a fiddle for demonstration purposes, but you can see the problem here. I want the ordered list on t ...

CSS Conditional Enrollment feature malfunctioning

Struggling to register a conditional CSS for a SharePoint 2013 masterpage. No matter what style I apply, the layout remains unchanged. After researching, it seems like this is how I should register the CSS: <SharePoint:CssRegistration ID="CssRegistra ...

Tips for Modifying CSS Design for Unhovered Elements

HTML <ul id="menu"> <li><a href="#">Home</a></li> <li><a href="#">Categories</a> <ul> <li><a href="#">1</a></li> < ...

Press the "Enter" key to automatically submit the form and validate the input

How can I make my form submit when the "enter" key is pressed? Currently, I have set the button type as "submit" so that the form is submitted when enter is pressed. However, I also want to call a function with validation and confirmation. Right now, it&ap ...

What could be causing the header of the datatable to be out of alignment with the rest of

I'm facing an issue with my datatable where the header is misaligned with the content. Can someone please assist me in adjusting the header and content so that they are parallel? It doesn't look right at the moment. <div style="margin-top:1 ...

Traversing through an array and populating a dropdown menu in Angular

Alright, here's the scoop on my dataset: people = [ { name: "Bob", age: "27", occupation: "Painter" }, { name: "Barry", age: "35", occupation: "Shop Assistant" }, { name: "Marvin", a ...

What is the best way to retrieve data from a database, display it in an editable table, and then export

After searching diligently, I have been unable to find a table or data grid that is editable and capable of retrieving data from a MySQL database. My attempts with Slickgrid proved challenging due to the lack of documentation and complexity in making it op ...

After hovering, move the cursor into the input field

I currently have a form that is hidden by default using display:none. When I hover over another link, the form becomes visible. Is there a way to automatically place the cursor in the input field when this happens using CSS? If I change the form's di ...

What could be the reason for the CSS file not getting applied to the HTML in my project?

Having trouble applying an external CSS file to my HTML file. Currently working on a Cloud IDE (goormIDE, similar to C9) and trying to link an external CSS file to my HTML file on the web server using Node.js. However, the CSS file is not being applied to ...

Select a specific item from an array and reveal the corresponding item at the matching index in a separate array

I'm working on a project where I have a list of elements that are displayed using a ng-repeat and I am using ng-click to retrieve the index of the element in the array that I clicked on. Here is the HTML code snippet: <ul> <li ng-repeat=" ...

Implementing Bootstrap 4 Beta's server-side validation post error resolution

I'm currently working with Bootstrap 4.0.0.beta and am facing an issue with server-side validation. When adding the .is-invalid class to inputs that were invalid upon submission, even after the user corrects the error, the class remains, potentially c ...

Mastering the art of customizing jQuery Mobile skins

Just landed a front end developer role at a prominent bank where I'll be focusing on the UI using jQuery Mobile. I'm looking for a comprehensive page that contains all the assets of jQuery Mobile to streamline the skinning process. Any leads? ...

Styling does not affect an Angular component that is injected into an iframe

I am facing an issue with styling in an iframe when trying to append my own angular component. Despite various attempts, I have been unsuccessful in getting the styling to apply to the component within the iframe. Upon loading the iframe, I use JavaScript ...

Creating distinct web addresses for various sections of vue.js pagination

I've implemented pagination using vue.js for my website's gallery. However, I'm facing an issue where the URL doesn't change when navigating through pages and upon page refresh, it always resets to page 1. My goal is to have the URL ref ...

What steps can I take to address security issues related to iframes?

Are there other security risks to consider when using iframes besides XSS vulnerabilities? How can I ensure that my website is secure when utilizing iframes? I've seen some JavaScript code that uses top.window, but I'm hesitant to rely on client ...

Tips for positioning "THANK YOU" in the center

and this is a snippet of my coding <div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class=" ...