Published on

How to Style <a> Links in React with Tailwind CSS

Authors
  • Name
    Ripal & Zalak
    Twitter

By default, Tailwind CSS removes the browser's default styling for anchor (<a>) links. This means that links will no longer be blue and underlined. You need to manually add styles back using Tailwind utilities.

To restore the default link styles in a React component, apply Tailwind classes directly:

const MyComponent = () => {
  return (
    <a
      href="https://example.com"
      className="text-blue-600 underline visited:text-purple-600 hover:text-blue-800"
    >
      Visit Example
    </a>
  )
}

If you want to style all <a> tags globally, use Tailwind’s @apply directive in your CSS file:

@tailwind base;
@tailwind components;
@tailwind utilities;

@layer base {
  a {
    @apply text-blue-600 underline visited:text-purple-600 hover:text-blue-800;
  }
}

This ensures that all links across your React app have consistent styling.

For better reusability, you can create a custom React component for styled links:

const StyledLink = ({ href, children }) => {
  return (
    <a href={href} className="text-blue-600 underline visited:text-purple-600 hover:text-blue-800">
      {children}
    </a>
  )
}

export default StyledLink

Now, you can use this component throughout your React app:

<StyledLink href="https://example.com">Go to Example</StyledLink>

Enabling visited: Styles in Tailwind 2

If you are using Tailwind 2.x, you need to enable the visited: variant in tailwind.config.js:

module.exports = {
  variants: {
    extend: {
      textColor: ['visited'],
    },
  },
}

This step is unnecessary in Tailwind 3.x, as visited: styles are enabled by default.

If you want external links to have an icon, you can use Tailwind's content utilities:

@layer base {
  a[target='_blank']::after {
    content: '🔗';
    margin-left: 4px;
  }
}

Sometimes, wrapping a button inside an <a> tag can cause unwanted styling. Instead, explicitly define styles only for text links:

.hyperlink {
  @apply text-blue-600 underline;
}

.hyperlink:visited {
  @apply text-purple-600;
}

Now, use the class only when needed:

<a href="https://example.com" className="hyperlink">Click me</a>
<a href="https://example.com"><button>Unstyled Button</button></a>

FAQs

Tailwind’s @tailwind base resets all browser default styles, including link colors and underlines, to provide a blank styling slate.

Yes, you can define global styles using @apply in a CSS file, or use a custom component for reusability.

Use Tailwind's state modifiers like this:

<a className="text-blue-600 underline visited:text-purple-600 hover:text-blue-800" href="#">
  Styled Link
</a>