Essay

Tutorial · November 28, 2023

Targeting only inline code elements with Tailwind Typography

Developers struggling to style inline code differently than code blocks within Tailwind's Typography plugin can now deploy a simple custom variant to gain granular control.

The Tailwind Typography plugin is a great way add beautiful styling to HTML rendered from Markdown, pulled from a CMS, or HTML you otherwise don't control.

Simply adding .prose to the container takes well-structured HTML and styles it in a reasonable way.

You can adjust the styles of individual elements with some of the prose modifiers supplied by Tailwind. For example, if you wanted to target the H1s in your content, you could add prose-h1:{utility} to your container.

<div class='prose prose-h1:text-green-800'>
    <!-- All your content goes here-->
</div>

Now all the H1s in the container will be rendered in text-green-800.

The only problem I've found so far is that the prose-code:{utility} modifiers affect both code in code blocks:

<pre><code>
    Like code in here
</code></pre>

and inline code: like code in here.

In many cases (including on this site), you'll want to treat the two very differently. I like to add a little background and border for inline code and add a lot more details for code blocks.

Tailwind plugin

To only target inline code, we can write a Tailwind plugin to add a custom variant.

To target inline code with CSS, we could use this selector:

:not(pre) > code {
    /* Inline code only */
}

To add an prose-inline-code:{utility} variant to Tailwind, we'll need to be a bit more specific to match the other Prose styles.

Add this to your tailwind.config.js and you'll now have a prose-inline-code variant you can use.

/** @type {import('tailwindcss').Config} */
const plugin = require('tailwindcss/plugin')

module.exports = {
  plugins: [
    require('@tailwindcss/typography'),
    
    plugin(function ({addVariant}) {
      addVariant(
        'prose-inline-code',
        '&.prose :where(:not(pre)>code):not(:where([class~="not-prose"] *))'
      );
    })
  ],
};

Usage

You can use the new variant just like you do all the other prose variants:

<div class="prose prose-inline-code:rounded prose-inline-code:border">
    <!-- All your content goes here -->
</div>

I'll open an issue on the Typography plugin to see if the team wants to merge it, and I'll update this post if it gets merged!

Details
Published
November 28, 2023
Reading
1 min
Words
325
Newsletter

Every week: the best things I've found and what I've been thinking about.

 

Related
  1. Apr 2025A cookieless, cache-friendly image proxy in Laravel (inspired by Cloudflare)
  2. Nov 2024Reservable models in Laravel
  3. Nov 2024Make 5x faster outbound requests in Laravel
Colophon

Set in Tiempos and IBM Plex Mono on a 22px baseline.

Thanks for spending a little of your day here.