- Published on
How to Style <a> Links in React with Tailwind CSS
- Authors
- Name
- Ripal & Zalak
How to Style <a> Links in React with Tailwind CSS
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.
Default Styling for Links in Tailwind CSS
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>
)
}
Using Tailwind's @apply for Global Link Styling
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.
Creating a Custom Link Component
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.
Additional Link Styling Techniques
1. Styling External Links
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;
}
}
2. Removing Link Styles Inside Buttons
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
1. Why do links lose their default styles in Tailwind CSS?
Tailwind’s @tailwind base resets all browser default styles, including link colors and underlines, to provide a blank styling slate.
2. Can I use @apply in React for Tailwind link styles?
Yes, you can define global styles using @apply in a CSS file, or use a custom component for reusability.
3. How do I add hover and visited styles to links in Tailwind?
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>
