What is the reason behind the change in style hierarchy when using ':last-child'?

I found myself in a confusing situation where using :last-child is affecting how parent classes are being applied.

The task at hand is to style the last element in a list of elements.

However, upon using :last-child, the priority of styles shifts and one of the parent classes stops working, requiring the use of !important to resolve the issue.

I have created a simple demonstration here: http://jsfiddle.net/wC2AX/1/

HTML:

<div class="hover">
    <div class="focus_on_last_child" style="background-color:red; width:100px;  height:100px">
        <div class="attribution">

        </div>
    </div>
</div>

CSS:

/*this should be applied on hover always*/
.hover:hover .attribution{
        background-color: black; /*try adding !important*/
        bottom: 0px;

}

/*basic properties*/
.attribution {
    height: 60px;
    overflow: hidden;
    position: absolute;
    bottom: -60px;
    width: 100px;
}

/*depending on a screen size styles are changed*/
.focus_on_last_child:last-child .attribution { /*try removing :last:child*/
    background-color: pink;
    bottom: -30px;
}

This example may seem trivial, but the intention is that styles change on hover. However, it only works when either !important is used or :last-child is removed.

Any suggestions are greatly appreciated!

Answer №1

This issue pertains to the specificity of selectors.

The first rule contains two classes and a pseudo-class:

.hover:hover .attribution

Similarly, the last rule also includes two classes and a pseudo-class (the :last-child):

.focus_on_last_child:last-child .attribution

Given that both rules have equal specificity, the one written later will take precedence. Removing the :last-child pseudo-class leaves only the two class selectors, reducing the specificity of the rule and allowing the :hover rule to take precedence.

To resolve this, it is recommended to reposition your :hover rule beneath your :last-child rule so that the latter takes priority, eliminating the need for using !important.

Answer №2

The reason for this is:

.hover:hover .attribution{

Is considered more targeted compared to:

.focus_on_last_child .attribution {

By including .hover, the specificity increases and the selector will function as intended:

.hover .focus_on_last_child .attribution {

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

Tips for adjusting the placement of enlarged images within colorbox

I recently discovered colorbox and decided to use it as my lightbox solution. However, I encountered a challenge with positioning the background (#cboxOverlay). I wanted to move it 120px to the left so that some content from the original page would still ...

Creating a dynamic mouse trail effect using CSS and JavaScript without compromising element clickability

I'm looking to create a mouse trail that follows the cursor as it moves, made up of small icons or images that gradually fade out over time. I attempted to achieve this by overlaying a grid on top of all other elements on the page. The grid consists o ...

How to place a button in the bottom center of a panel using asp.net

After learning about centering a button at the bottom-center inside a div, it became clear that it's similar to centering a button within a panel. I managed to achieve this by adding the following CSS to the button: position:absolute; margin-left ...

Tips for aligning three cards in a row using Bootstrap-5

In my Django template for loop, I am trying to display the first three cards from the database on the same line. Currently, only two of them are staying on the same line and I want all three cards to be aligned horizontally. <div class="row"&g ...

JQuery Mobile: Adding fresh, dynamic content - CSS fails to take effect

I've encountered this issue before, but I'm still struggling to resolve it. When adding dynamic content to a page (specifically a list-view), the CSS seems to disappear once the content is added. I've tried using the trigger("create") functi ...

What is the best way to update specific content with fresh URLs?

I am interested in keeping certain sections of my page static, such as the header and footer, while allowing the main content to change dynamically. Additionally, I would like the URL to update based on the new content being displayed. Although I am famil ...

How to align an unordered list vertically in the center using Bootstrap?

Trying to figure out why the ul within this parent div is not centered vertically. Here is a screenshot of the issue: https://i.sstatic.net/ZOc9M.png <div className=" d-flex align-items-center bg-primary "> <ul ...

Having trouble with setting an image as a background in CSS for Nativescript on iOS?

In my NativeScript app, I am trying to set an image as the background using the CSS property background-image: url("res://ic_more"). It works perfectly on Android, but unfortunately, it does not display on iOS devices. I have confirmed that the image is l ...

The rows-per-page menu option in Vuetify suddenly vanishes

I'm currently working on incorporating a v-data-table inside a v-card, you can view the code in this CodePen snippet: https://codepen.io/benwasin97/pen/eYveZGL <v-data-table :headers="headers" :items="items" ...

Combining Node and React: Using CSS Class Names with Hyphens

Currently, my project utilizes react-starter-kit and includes several react components, each with its own styling file (scss). Every component imports the styling file at the top like this: import s from './Header.scss'; When it comes to using ...

The CSS styling in Internet Explorer 11 is causing cells to merge into the same column in a table

In my CSS-styled form that resembles a table, the two input elements are displaying on top of each other instead of side by side. How can I adjust them to appear next to each other? There is a possibility that this issue could be browser-specific. The for ...

Uncertainty about the integration of a JavaScript file into a PHP file

Having two PHP files where one is executed through a URL and makes AJAX calls to the second PHP file can present challenges. Sometimes, the AJAX results return HTML content with JavaScript events that do not work as expected. To solve this issue, I have in ...

It is not possible to dynamically change the value of a checkbox using jQuery when it is checked or

When the checkbox value is changed to 1, it cannot be changed back to 0 when unchecked. $('.ChkBox').change(function() { if ($(this).attr('checked')) { $(this).val('1'); } else { $(this).val('0'); } ...

`Gradient blending in ChartJS`

Currently, I am facing an issue with my line chart having 2 datasets filled with gradients that overlap, causing a significant color change in the 'bottom' dataset. Check out my Codepen for reference: https://codepen.io/SimeriaIonut/pen/ydjdLz ...

Modify visibility or enable state of a text box according to a checkbox in PHP

Currently, I am utilizing PHP to exhibit a vertical list of numbered checkboxes, with one checkbox for each day in a specific month. Next to every checkbox, there is a text box where users can input optional notes for the selected day. To ensure that users ...

Clicking a link will trigger a page refresh and the loading of a new div

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.3/jquery.min.js"></script> $(window).load(function () { var divs = $( #add_new, #details"); $("li a").click(function () { ...

Tips for deleting HTML tags from a database

Whenever I add something to my database, it also includes the html tags. Is there a way to prevent this from happening? public function retrieveDataFromDatabase() { $query = "SELECT * FROM gb ORDER BY id DESC LIMIT 0, 4"; //data output if ...

Tips for creating a deepCss selector for an input Textbox in Protractor

When I attempt to use sendKeys in an input textbox with Protractor, the element is located within a shadow-root and there are three separate input textboxes. ...

SweetAlert html is not recognizing ng-app, but it functions correctly within the html body

When inserting a bootstrap table inside a SweetAlert, I encountered an issue where using ng-app or ng-repeat to populate data inside the table's rows did not call ng-app. However, when populating the table outside of the SweetAlert in the body, ng-app ...

Verify whether a div element is styled in a specific manner

Upon initial load of my website, if the page is maximized or in fullscreen mode, the comBrand div will have specific CSS properties applied. However, during a resize event, I use the .css() function to adjust the properties of this element so it doesn&apos ...