Group list of elements by arbitrary attribute with CSS

Viewed 29

I'm trying to visually group a list of elements by generating a header above every break in the sequence of attributes. I've been able to accomplish it when the group names are known ahead of time. But what if I want to support an unknown variety of groups? Is it possible to determine a match when the actual attribute value is a variable?

This is how it currently works with the attributes values predefined. It's not very extensible.

https://jsfiddle.net/6g7qesja/1/

CSS

.item:first-child:before,
.item:not([data-group="First Group"]) + .item[data-group="First Group"]:before,
.item:not([data-group="Second Group"]) + .item[data-group="Second Group"]:before,
.item:not([data-group="Third Group"]) + .item[data-group="Third Group"]:before {
    content: attr(data-group);
    display: block;
    font-weight: bold;
}

HTML

<div class="item" data-group="First Group">one</div>
<div class="item" data-group="First Group">two</div>
<div class="item" data-group="First Group">three</div>
<div class="item" data-group="Second Group">four</div>
<div class="item" data-group="Second Group">five</div>
<div class="item" data-group="Second Group">six</div>
<div class="item" data-group="Third Group">seven</div>
<div class="item" data-group="Third Group">eight</div>
<div class="item" data-group="Third Group">nine</div>

RENDERS

First Group

one

two

three

Second Group

four

five

six

Third Group

seven

eight

nine

0 Answers
Related