Kinda silly sounding, isn’t it? CSS database queries. But, hey, CSS is capable of talking to other languages in the sense that it can set the values of things that they can read. Plus, CSS can request other files, and I suppose a server could respond to that request with something it requested from a database.
But I’m getting ahead of myself. The idea of CSS database queries was a joke tweet going around the other day about recruiters looking for a developer who can connect to a database with CSS. Lee Meichin wrote “Yes, I can connect to a DB in CSS” as an equally funny retort.
![Screenshot of a tweet sarcastically looking for someone who can do CSS database queries.](https://i0.wp.com/css-tricks.com/wp-content/uploads/2022/02/tweet.jpg?resize=828%2C567&ssl=1)
What’s the trick behind CSS database queries?
It’s nicely elaborate:
- Use a hand-modified-to-ESM version of SQL.js, which is SQLite in JavaScript.
- Get a database ready that SQL.js can query.
- Build a Houdini
PaintWorklet
that executes queries in JavaScript and paints the results back to the screen in that<canvas>
-y way thatPaintWorklets
do. - Pass the query you want to run into the worklet by way of a CSS custom property.
So, the usage is like this in the end:
<script>
CSS.paintWorklet.addModule('./cssdb.js')
</script>
<style>
main {
--sql-query: SELECT name FROM test;
background: paint(sql-db);
}
</style>
Which, you gotta admit, is connecting and querying a database in CSS.
This reminds me that Simon Willison did this last year with a totally different approach. His concept was that you have RESTful endpoints, like /api/roadside_attractions
, that return JSON data. But then as an alternative endpoint, you could make that /api/roadside_attractions.css
which would return a valid CSS file with all the data as CSS custom properties.
So, instead it looks like this:
<link rel="stylesheet" href="/api/roadside_attractions.css">
<style>
.attraction-name:after { content: var(--name); }
.attraction-address:after { content: var(--address); }
</style>
<p class="attraction-name">Attraction name: </p>
<p class="attraction-address">Address: </p>
Which, again, is essentially connecting to a database in CSS (with HTML required, though). You can literally see it work.
If you use js, it’s not connecting using css.
The query is in the CSS, like the title says.
The initial call is in CSS even though what it’s calling is JavaScript. So technically it’s connecting via CSS if you squint hard enough
Chris you need to delete this before we see this as a position requirement
What is the motivation to do so? What is the advantages of that usage?
The motivation is that it is your job. The advantages of this are clear, the long-term viability of this approach defines our architectural archetype. This allows us to ensure a clean development cycle, while reducing white noise like Toxic Code Bloat (TCB). As you grow in your career, you’ll begin to appreciate this sort of thing.
this is hilarious. love it!