Targeting only inline code elements with Tailwind Typography

November 28, 2023

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>
Code highlighting powered by torchlight.dev (A service I created!)

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!

Me

Thanks for reading! My name is Aaron and I'm a Developer Educator at PlanetScale — a MySQL platform.

If you ever have any questions or want to chat, I'm always on Twitter.

You can find me on YouTube on my personal channel or my work channel, or my behind the scenes channel.