Selecting sibling elements based on their position in the hierarchy can be achieved using a CSS selector that targets

In the scenario where there is an HTML element with multiple siblings:

    <div id=parent>
        <div></div>
        <div></div>
        <div></div>
        ...
        <div id=fourthToLast></div>
        <div></div>
        <div id=penultimate></div>
        <div></div>
    </div>

The penulimate and the fourthToLast siblings have unique requirements: One of them - never both - should be displayed at different widths based on media breakpoints and total number of siblings.

I've attempted to use pseudo-selectors in my CSS code:

silibingNrOf(#penultimate) mod x = y

For instance, if there are a total of 15 siblings inside the parent element, then silibingNrOf(#penultimate) will be 14.
silibingNrOf(#penultimate) mod 3 would return 2.

I am struggling to find the correct CSS selector syntax for this situation:

    #fourthToLast, #penultimate { display: none; }

    @media screen and (min-width: 400px) {
        
        if silibingNrOf(#penultimate) mod 2 = 0 {
            #penultimate { width: 25%; display: block; }
        }
        
        @media screen and (min-width: 800px) {
        
            #penultimate { display: none; }
        
            if silibingNrOf(#penultimate) mod 3 = 2 {
                #penultimate { width: 33%; display: block; }
            }

            if silibingNrOf(#penultimate) mod 3 = 0 {
                #fourthToLast { width: 16.666%; display: block; }
            }   
        
       }
    }

Answer №1

Update: An alternative approach would be to employ :nth-of-type(3n) for elements where

silibingNrOf(#penultimate) mod 3 = 0
, and utilize :nth-of-type(3n+2) for cases where
silibingNrOf(#penultimate) mod 3 = 2
. Additionally, you can use :nth-of-type(even) or :nth-of-type(2n) for scenarios where
silibingNrOf(#penultimate) mod 2 = 0
, as previously mentioned. Instead of solely relying on Javascript like my initial response suggested, the same results could have been achieved using :nth-child() with identical parameters. This realization only surfaced after your feedback.

Prior solution: One feasible method in JavaScript is depicted below:

const parent = document.getElementById("parent");
const parentChildrenCount = parent.childElementCount; 
if(parentChildrenCount % 2 === 1){
    parent.addClass("even"); // silibingNrOf(#penultimate) mod 2 = 0
}
if(parentChildrenCount % 3 === 1){
    parent.addClass("triple"); // silibingNrOf(#penultimate) mod 3 = 0
}
else if(parentChildrenCount % 3 === 0){
    parent.addClass("almost-triple"); // silibingNrOf(#penultimate) mod 3 = 2
}

Subsequently, these specified classes can be employed in your Sass code to target the respective elements. Furthermore, selectors such as penultimate and fourthToLast may be designated using the :nth-last-child pseudoselector.

Answer №2

Considering the setup outlined in the query along with all its possibilities, ranging from 1 to 7 components (including 'penultimate' and 'fourthToLast'). The vacant elements previously known as 'penultimate' and 'fourthToLast' do not necessitate an ID for this purpose.


    <div id=parent1>
        <div></div>
        <div>Content 1</div>
    </div>
    
    <div id=parent2>
        <div></div> 
        <div>Content 1</div>
        <div></div> 
        <div>Content 2</div>
    </div>
    
    <div id=parent3>
        <div>Content 1</div>
        <div></div>
        <div>Content 2</div>
        <div></div>
        <div>Content 3</div>
    </div>
    
    <div id=parent4>
        <div>Content 1</div>
        <div>Content 2</div>
        <div></div>
        <div>Content 3</div>
        <div></div>
        <div>Content 4</div>
    </div>
    
    <div id=parent5>
        <div>Content 1</div>
        <div>Content 2</div>
        <div>Content 3</div>
        <div></div>
        <div>Content 4</div>
        <div></div>
        <div>Content 5</div>
    </div>
    
    <div id=parent6>
        <div>Content 1</div>
        <div>Content 2</div>
        <div>Content 3</div>
        <div>Content 4</div>
        <div></div>
        <div>Content 5</div>
        <div></div>
        <div>Content 6</div>
    </div>
    
    <div id=parent7>
        <div>Content 1</div>
        <div>Content 2</div>
        <div>Content 3</div>
        <div>Content 4</div>
        <div>Content 5</div>
        <div></div>
        <div>Content 6</div>
        <div></div>
        <div>Content 7</div>
    </div>

The objective is

Initially hide the two (non-core) additional child elements,
which will consistently be the penultimate and fourth-to-last child.

if screen width is 400px ≤ x < 800px
    if count of core children is odd
        show the penultimate child at a 25% width

if screen width ≥ 800px
    if count of core children mod 3 equals 2
        present the penultimate child with a width of 16.66%

    if count of core children mod 3 equals 1
        showcase the fourth-to-last child with a width of 33.33%

To tackle this challenge without javascript and excluding functions that are not universally supported by all browsers (:has() / Firefox).

Solution:

:is(#parent1, #parent2, #parent3, #parent4, #parent5, #parent6, #parent7) {

    div:nth-last-child(2) {
        display: none;

        @media screen and (min-width: 400px) {
            &:is(:first-child, :nth-of-type(even)) {
                width: 25%;
                display: block;
            }
            @media screen and (min-width: 800px) {          
                &:nth-of-type(even) {
                    display: none;
                }
                &:is(:first-child, :nth-of-type(3n + 2)) {
                    width: 33.33%;
                    display: block;
                }
            }
        }
    }

    div:nth-last-child(4) {
        display: none;

        @media screen and (min-width: 800px) {
            &:nth-child(3n + 1) {
                width: 16.66%;
                display: block;
            }
        }
    }
}

Credits to David Thomas for his highly informative jsfiddle that guided me in the right direction.

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

The issue with the smooth scrolling feature in next/link has not been resolved

I am currently facing an issue where smooth scrolling is not working when using next/Link, but it works perfectly fine with anchor tags. However, the downside of using anchor tags is that the page reloads each time, whereas next/link does not reload the pa ...

Loading CSS resources in advance can still cause rendering delays

Trying to preload CSS using a link tag with the "preload" attribute set Place this inside the Head tag: <link rel="preload" href="css/layout.css" as="style"> Then add this script at the bottom of the Body tag (although placement shouldn't mat ...

How to make an HTML element draggable without the need for an ID

I am currently working on making dynamically created divs draggable. While I have successfully achieved this with pre-existing div elements as shown below: <div> This can be dragged around, but outputs cannot?! </div> the issue arises when ...

Is it possible to make an HTML page permanent and uneditable?

Is it possible to secure my HTML file from being edited or modified, especially in a web browser? Discover innovative techniques and gain deeper insights into web development and website design. Interested in learning more about HTML, CSS, JavaScript, PH ...

When I attempt to incorporate multiple sliders on a single page, I encounter difficulties in determining the accurate stopping position if the number of slides varies

I am having trouble setting the correct stop position for sliders with different numbers of slides on a page. When I have the same number of slides in each slider, everything works fine. However, I need to have a different number of slides in each slider ...

Tips for designing a webpage where a div element adjusts to fit the screen, regardless of the width of the content inside

Can CSS3 or a JavaScript library be used to create a webpage with a div that contains content wider than the screen, such as a large image or newsletter, and still fits it to the screen without scrolling or clipping any content? Below is an image demonst ...

When I try to expand the width of a div, the display property set to inline

Visit my website At the moment, my website features the following code snippet: <div class="main-sale"> <div class="time-left">Sale Ends in: </div> <div class="sale-item"> //Highlighted Sale it ...

Tips for saving the circular slider value to a variable and showcasing it in the console

I have coded a round slider and need assistance with storing the slider value in a variable and displaying it in the console using JavaScript. I want to store the tooltip value in a variable for future use. $("#slider").roundSlider({ radius: 180, min ...

Expanding on the specific properties of a parent component to its child, using SASS's extend feature

Can selected or specific properties be shared/extended from the parent to the child without the need to create a variable? .main-container { padding: 20px; margin: 20px; ul { padding:$parentPadding(); margin: 0; } ...

Hiding the overflow conceals the entire image in one direction, while leaving the other exposed

Here is the code I have written for my project (view fiddle here): img { width: 200px; height: 200px; } .image-container { width: 600px; height: 200px; overflow: hidden; } I am working with multiple images, all sized at 200px by 200p ...

aligning elements on various screens

Is there a way to achieve this layout on various screen sizes? The grey rectangles represent divs with content. Picture 1 (left) is for normal widescreen displays, picture 2 (middle) caters to smaller screens like netbooks or tablets, and picture 3 (righ ...

Using the "margin: auto" property to center the text box

I am having trouble centering the search box. I tried adding marginLeft: "auto",marginRight: "auto" to the search class but it's not working. Can you please advise me on how to fix this issue? Below is my code snippet and a link to the sandbox: https ...

What steps can be taken to ensure an animation does not continually reset to its original state when run infinitely?

I am looking to create an animation that continues infinitely without returning to its original state after completion, similar to a sun moving animation. Below is a sample project: .animator3{ -webkit-animation-name:j3; -webkit-animation-delay:0s; -web ...

Two divisions placed side by side

The current structure I am working with looks like this: <div id="container"> <div id="msg"><p>Lorem ipsum dolor sit amet.</p></div> <div id="img"><div id="content"></div></div> </div> # ...

Implementing jQuery code to increase the height of a Text Area dynamically

I have a situation where my asp textbox and label are appearing as a text area: <div class="control"> <asp:TextBox runat="server" Rows="2" ID="TextBox1" Width="80%" EnableViewState="false" ViewStateMode="Disabled" CssClass="textboxBootstr ...

Toggle the current list item in Jquery to expand to 100% width, while simultaneously shifting any adjacent items on the left and right downwards if present

I am working with a list (ul) that contains multiple items displayed in a tiled format. Each item has a brief introduction and can expand to show more information when clicked on. What I would like to achieve is for the expanded item to take up the entire ...

Enhance user experience with dynamic color changes in JavaScript

Looking to create a navigation menu with unique colors for each selected state? Check out the code below! After searching extensively, I stumbled upon this snippet. While it only includes one selected state, you can easily customize it for three different ...

Nginx and Django encountering issues with loading css files on a production server

I've come across several similar posts, but none of the solutions seem to work for me. Every time I load my static files, the browser throws errors like these: When I collect static files, everything works fine. Even running findstatic points me to t ...

Which shortcuts or techniques in jQuery/JavaScript can I implement to simplify this code further?

I've written a script to handle responsive design for smaller devices and display a toggle menu instead of a full-width menu. The current script works, but I find it messy. How can I make this code more minimalistic and efficient? Is it good practice ...

How to style CSS to ensure printed table content fits perfectly within the page

Does anyone know how to resize the contents of a table using CSS so that everything shows up when printing, without wrapping text in individual cells? In this scenario, <table class="datatables" id="table1"> <tr> <td style="white-space:nowr ...