Styling group headers within an unordered list using pure CSS - possible?

Hey there, I'm looking to spruce up my UL by adding group headers.

Here's a sneak peek at the structure I have in mind (keep in mind this is generated dynamically from a database):

<ul>
  <li class='group group-1'>
    <div>Group 1</div>
    ABC
  </li>
  <li class='group group-1'>
    <div>Group 1</div>
    DEF
  </li>
  <li class='group group-2'>
    <div>Group 2</div>
    GHI
  </li>
  <li class='group group-2'>
    <div>Group 2</div>
    JKL
  </li>
  <li class='group group-3'>
    <div>Group 3</div>
    MNO
  </li>
<ul>

I'd like to showcase only the initial group header DIV's of each unique group. The redundant group headers should be concealed.

Just a heads up, group names (like 1, 2, 3, etc.) will differ as they correspond to IDs within the database.

Is it feasible to achieve this using solely CSS? Let me know!

Answer №1

To apply the desired styling, you will need to target each selector individually:

[class*="group-1"] + [class*="group-1"] div,
[class*="group-2"] + [class*="group-2"] div ,
[class*="group-3"] + [class*="group-3"] div 
/* and so forth */{
  display:none;
}

[class*="group-1"] + [class*="group-1"] div,
[class*="group-2"] + [class*="group-2"] div,
[class*="group-3"] + [class*="group-3"] div{
  display:none;
}
<ul>
  <li class='group group-1'>
    <div>Group 1</div>
    ABC
  </li>
  <li class='group group-1'>
    <div>Group 1</div>
    DEF
  </li>
  <li class='group group-2'>
    <div>Group 2</div>
    GHI
  </li>
  <li class='group group-2'>
    <div>Group 2</div>
    JKL
  </li>
  <li class='group group-3'>
    <div>Group 3</div>
    MNO
  </li>
<ul>

Answer №2

The CSS ~Selector is a powerful tool for targeting all subsequent siblings. By using

.group-1 ~ .group1 { display: none; }
, you can hide all elements with the class .group-1 except for the first one.

Even dynamic group names can be targeted easily using the [attribute] Selector. For example, [class*="group-"] targets any element with a class containing "group-".

Unfortunately, it's not possible to combine these two selectors in CSS alone to capture the wildcard value.

To achieve this effect, you would need to generate all possible class names (perhaps using SASS) and then use the ~Selector as demonstrated in this working example:

http://codepen.io/MattDiMu/pen/WxvGqe

In most cases, generating all possible IDs as classes is not a recommended solution due to its complexity.

Answer №3

If your structure remains the same, you will need to find a way to style elements using CSS that either:

  • Targets the first occurrence of an element with an unknown class name
  • Targets an element with an unknown class name following another element with the same class name in order to hide subsequent headers.

Unfortunately, achieving this is not possible, even with Selectors 4's :nth-child(An+B of S) notation since the class names are not predetermined.

If you can modify your HTML markup, consider organizing groups into separate UL elements each with its own header for better semantics.

However, if there is no control over the markup, you may use JavaScript to add a specific class to the first LI of each group and then apply styling to hide .group:not(.first) > DIV (where "first" is the additional class).

Answer №4

One way to achieve this is by using the CSS + combinator.

.section-1 + .section-1,
.section-2 + .section-2,
.section-3 + .section-3 {
  display:none;
}

Answer №5

CSS has the limitation of only being able to change statically defined elements, but what if you want to work dynamically? In that case, you can incorporate a little bit of javascript into your solution. The approach involves hiding all the li elements using CSS initially, and then selectively showing the first li element with a unique class.

window.onload = function () {
    
    'use strict';
    
    var liClasses = [];
    var liClass, i;
    
    var liLeng = document.querySelectorAll('li').length;
    
    for ( i = 0; i < liLeng; i++ ) {
        liClass = document.getElementsByTagName('li')[i].getAttribute('class');
        liClasses.push(liClass);
        
        document.getElementsByClassName(liClasses[i])[0].style.display = 'block';
        document.getElementsByTagName('p')[0].innerHTML = liClasses;
    }
    
};
ul {
    padding: 0;
    margin: 0;
    list-style-type: none;
}

li {
    width: 150px;
    height: 50px;
    display: block;
    background-color: aqua;
    display: none
}

li:nth-of-type(even) {
    background-color: antiquewhite
}

p {
    width: 200px;
    height: 50px;
    background-color: coral
}
<div class="t">
  <ul>
    <li class="test elm1">1</li>
    <li class="test elm1">1</li>
    <li class="test elm2">2</li>
    <li class="test elm3">3</li>
    <li class="test elm4">4</li>
    <li class="test elm4">4</li>
    <li class="test elm5">5</li>
    <li class="test elm6">6</li>
    <li class="test elm7">7</li>
    <li class="test elm7">7</li>
    <li class="test elm8">8</li>
    <li class="test elm5">5</li>
    <li class="test elm6">6</li>
    <li class="test elm7">7</li>
    <li class="test elm7">7</li>
    <li class="test elm8">8</li>
    <li class="test elm5">5</li>
    <li class="test elm6">6</li>
    <li class="test elm7">7</li>
    <li class="test elm7">7</li>
    <li class="test elm8">8</li>
    <li class="test elm9">9</li>
    <li class="test elm10"></li>
  </ul>
</div>
<p></p>

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

What is the best way to apply styling to an image that is contained within the document.write function?

I'm looking to customize the design of this cat image, but I'm struggling to locate where to incorporate the div class. It's likely a basic step, but as a beginner in JavaScript, I'm hoping that someone can assist me. document.write(&ap ...

The overlay background is being obscured by surrounding elements

Hey there! I'm experimenting with some basic coding and ran into an issue with an overlay. Here's the site link: Sorry for the strange language. :-) If you click on the button with the tiny icon, you'll notice that the overlay form isn&apos ...

Unable to trigger JQuery .blur event

I am currently working on implementing server-side validation for an input field that needs to be validated when it loses focus. However, I'm running into an issue where the alert is not triggered when the input field loses focus. Here's a snipp ...

Is there a way to display images in Vuetify similar to the linked image below?

I am looking to measure my v-img like the one shown in the image below. https://i.stack.imgur.com/edMKr.jpg Does anyone know how I can achieve something similar to the image shown using vuetify's v-img. <div class="row"> <v ...

Using Cordova to create an accordion list on an HTML webpage

I am in need of an accordion list implementation for the given HTML code. I specifically want it to expand when 'Technical' is clicked, and collapse upon clicking again. Here is the HTML code: <!-- Techincal --> <div class= ...

The height of the Material UI Paper component is not appropriately matched with the parent component

I am currently working with the Paper component that contains a Card component, and I am trying to make its height fill the entire screen. To simplify the problem, I have provided the following code: import React from "react"; import { makeStyles ...

When utilizing CKEDITOR, the default TEXTAREA is obscured, and CKEDITOR does not appear

I am trying to incorporate CKEDITOR into my project. I have added the ckeditor script in the footer and replaced all instances of it. <script src="<?= site_url('theme/black/assets/plugins/ckeditor/ckeditor.min.js') ?>" type="text/javasc ...

Expanding div that adjusts to content size and expands to fit entire page

Appreciate your help. I'm currently facing an issue with the "content" and "footer" sections within the "wrapper" element. Below are the styles for these elements: #content { width: 100%; min-height: 100%; position: relative; background- ...

Having Multiple Login Forms on a Single Page

I have encountered an issue with my login form code. It works perfectly as a single form, but I need to have 20 of these forms on one page. Despite my efforts to duplicate the code for each new form and adjusting the IDs, I am unable to make more than one ...

Endlessly triggering document.execCommand, the JavaScript selectionchange-EventListener seems to have a mind of

I recently implemented an event listener for selectionchange in the following manner: document.addEventListener("selectionchange", function() { highlight(); console.log("selectionchange-triggered"); }, false); After that, I included the code bel ...

How to place a child <div> within a parent <div> that is fixed on the page

I am currently working on creating a modal window using HTML/CSS. My goal is to have the modal window fixed in position relative to the browser window, with a white background. Inside the modal, there will be an image at the top and a div element at the bo ...

Is there a different option available in place of the JavaScript confirm function?

I developed an application where I heavily utilized the javascript confirm function. confirm("Do you want to proceed"); However, I am not satisfied with the default appearance of the confirm dialog and would like to implement a customized version with be ...

Shift content from side to side with a click

I've been attempting to shift content left and right using an onclick event and I need it to stop at the margins on the left or right. The list-items are generated dynamically. Here's the code I've tried so far, but it's not quite worki ...

Angular dropdown tooltip for overflowing text

Here is the select element in question: <select id="select-full" title="Make selection" class="form-control form-custom input-sm" name="Select" ng-model="form.select" ng-options="select.displayName as select.text for select in selec ...

Creating a dynamic trio of graphs with HTML5, CSS3, and Vanilla JavaScript

I successfully created a tree graph using HTML5 and CSS3, but currently the nodes are static. I am looking to enhance the graph by making it dynamic. By dynamic, I mean that if the number of nodes increases or there are multiple children added, the graph ...

Focus on a specific button based on its text inside

Two buttons are present with the same class but different content <a class="button ordrViewBtn">Sold Out</a> <a class="button ordrViewBtn">Re-Sell</a> I want to change the color of the "Sold Out" button. Is it p ...

Issues with fonts in Google Chrome Version 32.0.1700.76 m

After recently updating my Google Chrome browser, I noticed that some of the fonts are not displaying correctly. Interestingly, they appear fine on other browsers, but the issue only seems to occur in Chrome v32.0.17...76 m. The fonts I used were "Open Sa ...

Utilizing jQuery to apply a class to an element and modify the CSS parameters with custom values simultaneously

Unsure if this idea is feasible, but I'll attempt to explain my requirements. I am interested in accomplishing something like the following: A CSS class with variables X, Y, and Z left undefined: .r {border-radius:Xpx;-webkit-border-radius:Ypx;-moz ...

HTML code for an admin login form

Looking for a way to create a login form without PHP in HTML for an administrator account, so the admin information remains secure and cannot be easily accessed from a database. Any suggestions or tips on how to achieve this? ...

Fluctuate the window.location with jQuery or javascript

My goal is to create a functionality where clicking an image will toggle the window.location url between '#' and '#footer'. The current code I have for this is: <script> function clickarrow(){ var rd=Math.floor(Math.random() ...