Explain Codes LogoExplain Codes Logo

How to remove only underline from a:before?

html
responsive-design
css
pseudo-elements
Alex KataevbyAlex Kataev·Feb 20, 2025
TLDR

Stripping the underline from the a:before pseudo-element can be achieved by applying the CSS rule, text-decoration: none;:

a:before { text-decoration: none; }

This is the simplest way of ensuring that your :before content remains free from any inherited text decoration.

Embracing text-decoration inheritance

Understanding how text-decoration interacts with pseudo-elements is the crux of completing this task with finesse. Here we go:

  • Chain of inheritance: Be aware that :before content by default inherits text decoration from its parent element.
  • Breaking the chain: Applying display: inline-block; for :before breaks the text-decoration inheritance — quite a stylish rebel, isn't it?
  • Hover issue: Be informed that display: inline-block; will give :before a blind eye to any text decoration from its parent on hover. Beware!

A peep into the world of browser quirks

To ensure your solution stands strong across different browsers, we need to consider browser quirks:

IE8-11 Display Bug

The navigating masters of Internet Explorer, versions 8 to 11, harbor a known bug with display: inline-block;. Something, that might slightly rock your layout or functionality boat.

For boats to sail smoothly across all the browser seas, here's your navigational map:

  • Use a local HTML page or tool like JSFiddle to test the waters of your solution.
  • If you encounter stormy weathers in legacy browser seas, have your conditional stylesheets or hacks lifeboats ready.

Cutting the edge with patterns and tricks

Pseudo-elements styling can sail beyond just removing underline. Here are some more co-travelers aboard your CSS voyage:

From space collapse to whitespace

Noticed your :before content gasping for breath with collapsed spaces after it? Give it a sigh of relief using white-space: pre;. Pseudo-element says "Thank You!".

Hover effects - A cat and mouse game!

Want to play the cat and mouse chase game by having hover effects on the parent element but not on your :before content? Here is your luring cheese!

a:hover:before { display: inline-block; text-decoration: none; /* "Catch me if you can!" says :before to underline 😜 */ }

Spanning the workaround galaxy

If display: inline-block; proves unsuitable, consider hopping onto the span galaxy. Tricking the span with styling can bypass pseudo-element limitations:

a:before { content: ""; /* Bye Bye underline...you won't be missed 😂 */ } a:hover span { text-decoration: underline; /* Bringing sexy underline back...but only for hover 🕺🏻 */ }