CSS cannot talk to a database directly, but it can set values that other languages read, and it can request files. In theory a server could answer such a request with data pulled from a database — which is roughly where the joke ends and two real implementations begin.

The origin: a joke and a rebuttal

The idea started as a joke tweet about recruiters searching for a developer who can connect to a database with CSS. Lee Meichin answered it with an equally funny retort, “Yes, I can connect to a DB in CSS.”

Screenshot of a tweet sarcastically looking for someone who can do CSS database queries.

Approach one: SQLite compiled to JavaScript, run inside a PaintWorklet

The first implementation is a four-step construction:

  1. Use a hand-modified-to-ESM version of SQL.js, which is SQLite compiled to JavaScript.
  2. Prepare a database that SQL.js can query.
  3. Build a Houdini PaintWorklet that runs the queries in JavaScript and paints the results to the screen the way PaintWorklets do, in their <canvas>-like fashion.
  4. Pass the query itself into the worklet through a CSS custom property.

From the outside, usage looks like this:

<script>
  CSS.paintWorklet.addModule('./cssdb.js')
</script>
<style>
  main {
    --sql-query: SELECT name FROM test;
    background: paint(sql-db);
  }
</style>

The query travels through CSS, executes against the database and returns painted output. By any fair description, that is connecting to and querying a database from CSS.

Approach two: serving data as custom properties over HTTP

Simon Willison had demonstrated a completely different route the year before. His concept: a RESTful endpoint such as /api/roadside_attractions returns JSON, while an alternate endpoint /api/roadside_attractions.css returns a valid CSS file carrying the same data as CSS custom properties.

Consuming it looks like this:

<link rel="stylesheet" href="https://css-tricks.com/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>

Again, a database effectively reached from CSS — though HTML is required here. A working demo is available on CodePen.