Sorting with CSS

Posted on August 22, 2014 by ebenpack

Prompted by the following question asked on

Hello, is it possible to sort something by popularity using only CSS and HTML? Or do i need to use something else like JS etc.?

- /u/justanewboy

I have devised the following solution:

1<!DOCTYPE html>
2<html lang="en">
4 <meta charset="UTF-8">
5 <title>Document</title>
6 <style>
7 .container {position: relative; height: 200px;}
8 .sorted {height:20px; position: absolute;}
9 .sorted[data-sort='1'] {top: 0;}
10 .sorted[data-sort='2'] {top: 20px;}
11 .sorted[data-sort='3'] {top: 40px;}
12 .sorted[data-sort='4'] {top: 60px;}
13 .sorted[data-sort='5'] {top: 80px;}
14 .sorted[data-sort='6'] {top: 100px;}
15 .sorted[data-sort='7'] {top: 120px;}
16 .sorted[data-sort='8'] {top: 140px;}
17 .sorted[data-sort='9'] {top: 160px;}
18 .sorted[data-sort='10'] {top: 180px;}
19 </style>
22 <div class="container">
23 <div class="sorted" data-sort="2">2</div>
24 <div class="sorted" data-sort="3">3</div>
25 <div class="sorted" data-sort="1">1</div>
26 <div class="sorted" data-sort="6">6</div>
27 <div class="sorted" data-sort="4">4</div>
28 <div class="sorted" data-sort="10">10</div>
29 <div class="sorted" data-sort="9">9</div>
30 <div class="sorted" data-sort="5">5</div>
31 <div class="sorted" data-sort="8">8</div>
32 <div class="sorted" data-sort="7">7</div>
33 </div>

Here's an example of it in action.


Have a look at the HTML and you'll see that these items are not represented in the markup in the order that you're seeing them on the page (assuming you're using a modern browser, and you don't have any sort of user stylesheet overriding these rules). Or better yet, try to select the text and see what horrors CSS hath wrought.

Of course it should go without saying that you should almost certainly never, ever do such a thing. But it's still interesting to see what CSS is capable of these days. To put it in bold letters: CSS sort is nowhere close to cross-browser compatible, and is almost certainly inappropriate for all real-world situations.

That said, I'm not sure if this could be generalized a bit more (i.e. to obviate the repetition of .sorted[data-sort='x'] {top:(20*x)px;}), but I'll be sure to edit this post with any new results I discover. I'm also curious about the time complexity of such a sorting algorithm. Intuition tells me it's likely to be something like O(n*log(selector)property). Don't quote me on that, though.

And finally, I apologize if this is old news. I couldn't find any references to anything similar to this, but I would not be surprised if this isn't a new discovery. If you know of prior art, let me know by submitting an issue on github.