Is it possible to choose only half of the elements using the :nth-child selector in

Consider this code snippet:

<ul>
  <li>Hello Universe</li>
  <li>Hello Universe</li>
  <li>Hello Universe</li>
  <li>Hello Universe</li>
</ul>

Can we select exactly half of the total elements by using :nth-child() or any other method? The goal is to target the first/last two li elements in the given example, and if the number of lis is increased to six, it should then target the first/last three.

It seems like I might need to resort to JavaScript for this...

Answer №1

If you're looking to style elements using only CSS, there's a way to select half of them... with a catch.
The only downside is that you need to know the exact total number of items in advance. It may work for 150 elements, but not for 151.

Check out this demo: http://jsfiddle.net/tcK3F/ (*)

Here's the basic CSS code:

/* Selecting half or more items. Up to 6 */
li:first-child:last-child,
li:nth-child(n+2):nth-last-child(-n+2),
li:nth-child(n+3):nth-last-child(-n+3),
li:nth-child(n+4):nth-last-child(-n+4),
li:nth-child(n+5):nth-last-child(-n+5),
li:nth-child(n+6):nth-last-child(-n+6) {
  color: white;
  background: darkblue;
}

/* Selecting half or less items. Up to 6 */
li:nth-child(n+2):last-child,
li:nth-child(n+3):nth-last-child(-n+2),
li:nth-child(n+4):nth-last-child(-n+3),
li:nth-child(n+5):nth-last-child(-n+4),
li:nth-child(n+6):nth-last-child(-n+5),
li:nth-child(n+7):nth-last-child(-n+6){
  font-style: italic;
  border: 2px solid red;
}

Inspired by:
This technique was inspired by André Luís and shared by Lea Verou in her post: Styling elements based on sibling count. I've tailored it for selecting specific portions of elements.

Quick breakdown:
Using :nth-last-child(-n+3) selects the last 3 items within a parent; while :nth-child(n+3) picks all items except the first 3. Combine them to target elements purely through CSS based on their position relative to others (or the number of children in a parent). However, be prepared to write out 75 of these selectors separated by commas if you want this method to apply to 150 elements... :)

Compatible with IE9+ (JS polyfills available)

(*)
first part of HTML code: even number of list items;
second part: odd number of list items

first CSS rule: targets the last N from a set of 2N items or the last N+1/2 items from 2N+1, styling them in white on blue (e.g., 3 items out of 5 or 6).
second CSS rule: will pick the last N from 2N items or last N-1/2 items from 2N+1 and style them with a red border and italic formatting (e.g., 2 items out of 4 or 5)

Answer №2

To achieve a similar effect with just CSS, you would need to utilize a selector for either nth-child(odd) or nth-child(even). However, if you specifically require the last half and not just odd or even elements, then JavaScript/jQuery is necessary.

With jQuery, you can target them like this:

var myList = $("ul li");

myList = myList.slice(0, Math.floor(myList.length/2));

Answer №3

Examples

Design a unique CSS class to style specific elements:

.custom {
    background-color: #18D;
}

Utilize jQuery to dynamically add the custom class to a set of elements:

$(function () {
  var $divs = $('div')
  var count = $divs.length

  // Add class to first half:
  $divs.slice(0, Math.floor(count / 2)).addClass('first')

  // Add class to last half:
  $divs.slice(count - Math.floor(count / 2)).addClass('first')
})

If you wish to include the middle element in case of an odd number of elements, modify Math.floor to Math.ceil. Explore all possibilities in the examples.

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

"Enhancing User Interaction: The Dynamic Trio of Ajax, Php, and MySql in Comment

I have successfully developed a basic commenting system, featuring a form with two fields: name and comment. Upon submitting the values, it utilizes Ajax to dynamically add the comment to the existing page without refreshing the entire content. My next ob ...

Adding AngularJS modules to an HTML file

Recently, I've been diving into the world of AngularJS, but I'm facing a roadblock - my HTML doesn't recognize the angular module I created. It's odd because the bindings work perfectly without involving the module... This is my HTML: ...

D3 group of legendary elements

Is there a way to group both the circle and text elements for each legend item together? I'm currently facing a challenge with the enter/exit methods. While I can create the groups (g), I'm unable to append the text and circle elements. li.sel ...

Is it necessary for me to include body, html at the beginning of my CSS code?

For all of my pages, I have been including the following code at the top. body { color: #333333; font-family: Arial,sans-serif; font-size: 0.95em; line-height: 1.15; } However, a colleague of mine has informed me that I only need to targ ...

Is there a way to stop my <pre> code from being displayed on the page?

Currently, I am utilizing the google code prettifier found at http://code.google.com/p/google-code-prettify/ This tool functions similarly to stack overflow by enhancing and highlighting syntax when a block of code is input. However, I have encountered a ...

Is there a way to automatically play videos without any audio?

Is there a way for my video to automatically start playing when the page loads, without sound? I want it to function similar to the video on this webpage: . I've experimented with various jQuery, JavaScript, and CSS techniques from online resources, ...

Tips for staying on the same tab after submitting the form

I have encountered an issue where I need to keep the current tab selected even after submitting a form or refreshing the page. This is how my View File appears: <ul class='tabs'> <li><a href='#tab1'>Tab 1< ...

Update the header by changing the background of all elements within it, while keeping the rest of the page as is

I am currently creating a Gatsby site with a layout and header component to construct pages. Each component has its own stylesheet (layout.module.scss and header.module.scss). Below is the code snippet: /* layout.js */ import React from "react" ...

What could be the reason for the state not initializing with the provided value?

It seems that the latest value is being passed through props, but when it is set as the initial value for state, it doesn't appear. https://i.stack.imgur.com/7dVf2.png import React, { useRef, useState } from "react"; //importing config fr ...

How to position two divs in a row using Bootstrap

Looking at the output below: https://i.stack.imgur.com/pQM8F.png The blue circle is placed in one div, while the text is in another. I'm perplexed by why the first div appears on top and the second doesn't seem to align properly. Here's th ...

Troubleshooting: Images not displaying properly in React due to Webpack configuration bottleneck,

I am facing an issue with loading images in my React application. Some images are set up in the CSS file like this: background-image: url('/../img/logo.png'); On the other hand, I would like to use images inside React components using the img ...

Setting the default value for ngModel does not receive any information from the model

I am trying to populate a form with default values using the code below: <h3>ِStart Time</h3> <div class="row" > <div class="col"> <label for="startTime">Hour(s) </label> <input type="numb ...

Difficulty viewing image in Firefox using HTML <img> tag

I'm encountering an issue with rendering an img tag in an HTML page. The img source is a file located on a remote server. Surprisingly, when attempting to display the image in Firefox using: file://///server/folder1/folder2/name.jpg it shows up prop ...

Steps to configure JavaScript to initially conceal a div within a continuous loop

I have implemented a JavaScript function to toggle the show/hide functionality of a div class. The content of the div and the button that triggers the toggle action are both inside a while loop. Initially, I used "div id" in my JavaScript code, but it was ...

What is the most common method for creating a dropdown menu for a website's navigation?

Is there a common approach to creating an interactive drop-down navigation menu in the industry? I have searched on Google and found multiple methods, but as a student working on my first big web project, I am hoping to find a standard practice. I don&apo ...

Picture emerges from the lineup

My dilemma involves repositioning an image within a row > col-md-6. To address this, I devised two classes - .pos1 and .pos2 .pos1 { position: relative; } .pos2 { position: absolute; right: 0px; } However, when applying these classes, the ...

Concentrate on the HTML element once it becomes active

I am facing a challenge where I need to focus on a specific input element. However, there is a spinner that appears on page load and remains hidden until certain http requests are completed. All inputs are disabled until the requests are finished. The setu ...

An irritating bug causing a 1px difference in Chrome 21

Hey there, I've encountered a strange issue with the datepicker on this website. It works perfectly fine on IE8+, Firefox 14, Chrome 20, and Opera 12. However, as soon as Chrome updated to version 21, things went haywire! I'm baffled and can&apos ...

Utilizing Google+ Snippet and Open Graph Protocol for Enhanced Visibility

I am currently facing an issue with my dynamically built web page where the links shared on Google+ are not showing snippets properly. I have followed the example snippet for article rendering and documentation provided here: https://developers.google.com ...

Avoiding scrolling when a button (enveloped in <Link> from react-scroll) is pressed in React

Currently, I am implementing the smooth scroll effect on a component using react-scroll. However, adding a button inside the component to create a favorite list has caused an issue where the smooth scroll effect is triggered upon clicking the button. Is ...