Skip to content

Styling <code> within an anchor element

I faced a snag in one of my recent projects, while styling a <code> element within a <a> element. The project uses Markdown to write contents, and uses Eleventy to render contents into HTML pages.

In Markdown, you write the code within an anchor like:

[`box-sizing`](https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing)

…and, it generates HTML like:

<a href="https://developer.mozilla.org/en-US/docs/Web/CSS/box-sizing"><code>box-sizing</code></a>

We were styling all <a> elements with an underline, and all code elements with a light background colour. When putting them together, we didn’t want the code elements within <a> to have an underline, instead a border to indicate that it is clickable. Seems straightforward and we wrote the code:

CSS
.fail-demo-prose a {
color: rgb(139, 92, 246);
text-decoration: underline;
}

.fail-demo-prose a:hover,
.fail-demo-prose a:active,
.fail-demo-prose a:focus
{
text-decoration: none;
}

.fail-demo-prose a code {
padding: 0.0625em 0.25em;
border: 1px solid;
background: rgb(237, 233, 254);

text-decoration: none; /* 😢 This don't work! */
}

.fail-demo-prose a:hover code,
.fail-demo-prose a:active code,
.fail-demo-prose a:focus code
{
color: rgb(237, 233, 254);
background-color: rgb(139, 92, 246);
border-color: rgb(139, 92, 246);
}

/* Presentational styles */
.fail-demo-prose > * + * {
margin-top: 1em;
}

.fail-demo-prose code {
text-shadow: none;
}
HTML
<div class="fail-demo-prose">
<p><a href="#">A regular link</a></p>
<p><a href="#"><code>'code' element within a link</code></a> 😢</p>
</div>
Preview

But, the underline on the code is still there! Bummer.

That’s when we learned the text-decoration is applied to all descendant inline text elements. And, styling child elements with text-decoration: none would not cause any change.

And we figured the fix is to make the <code> an inline-block! If you like to know why this works, go over the CSS spec.

CSS
.demo-prose a {
color: rgb(139, 92, 246);
text-decoration: underline;
}

.demo-prose a:hover,
.demo-prose a:active,
.demo-prose a:focus
{
text-decoration: none;
}

.demo-prose a code {
display: inline-block; /* 🔨 Whack! */
padding: 0.0625em 0.25em;
border: 1px solid;
background: rgb(237, 233, 254);

/* text-decoration: none; */ /* 👀 This is not required any more. */
}

.demo-prose a:hover code,
.demo-prose a:active code,
.demo-prose a:focus code
{
color: rgb(237, 233, 254);
background-color: rgb(139, 92, 246);
border-color: rgb(139, 92, 246);
}

/* Presentational styles */
.demo-prose > * + * {
margin-top: 1em;
}

.demo-prose code {
text-shadow: none;
}
HTML
<div class="demo-prose">
<p><a href="#">A regular link</a></p>
<p><a href="#"><code>'code' element within a link</code></a> 🎉</p>
</div>
Preview

I’m available for new projects from September 2021.

Get in touch