Anchor

An anchor is an HTML element (<a>) used to create hyperlinks that connect web pages and resources. Anchors are fundamental to web navigation and make the web "hyperlinked."

Basic Anchor Tag

html
<!-- Basic link -->
<a href="https://example.com">Visit Example</a>

<!-- Link to another page on same site -->
<a href="/about">About Us</a>

<!-- Link to section on same page -->
<a href="#contact">Jump to Contact</a>

<!-- Email link -->
<a href="mailto:[email protected]">Email Us</a>

<!-- Phone link -->
<a href="tel:+1234567890">Call Us</a>

Common Attributes

href (Hypertext Reference)

html
<!-- Absolute URL -->
<a href="https://example.com/page">External Link</a>

<!-- Relative URL -->
<a href="/products">Products</a>
<a href="./about.html">About</a>
<a href="../index.html">Go Up</a>

<!-- Anchor/Fragment -->
<a href="#top">Back to Top</a>

<!-- JavaScript pseudo-protocol (avoid) -->
<a href="javascript:void(0)" onclick="doSomething()">Click</a>

<!-- Download file -->
<a href="/files/document.pdf" download>Download PDF</a>

target

html
<!-- Open in new tab/window -->
<a href="https://example.com" target="_blank">
  New Tab
</a>

<!-- Open in same frame (default) -->
<a href="/page" target="_self">Same Window</a>

<!-- Open in parent frame -->
<a href="/page" target="_parent">Parent Frame</a>

<!-- Open in full window -->
<a href="/page" target="_top">Top Frame</a>

<!-- Named target -->
<a href="/page" target="my-frame">Named Frame</a>

rel (Relationship)

html
<!-- Security for external links -->
<a href="https://example.com" target="_blank" rel="noopener noreferrer">
  Secure External Link
</a>

<!-- SEO: Don't follow this link -->
<a href="/login" rel="nofollow">Login</a>

<!-- Sponsored/paid link -->
<a href="https://sponsor.com" rel="sponsored">Sponsor</a>

<!-- User-generated content -->
<a href="https://user-site.com" rel="ugc">User Link</a>

download

html
<!-- Prompt download with original filename -->
<a href="/files/report.pdf" download>
  Download Report
</a>

<!-- Suggest custom filename -->
<a href="/files/report.pdf" download="Q4-Report.pdf">
  Download Q4 Report
</a>

Anchor Links (Page Fragments)

Creating Anchor Points

html
<!-- Using id -->
<h2 id="services">Our Services</h2>

<!-- Link to anchor -->
<a href="#services">Jump to Services</a>

<!-- Link from another page -->
<a href="/about#team">About Our Team</a>

Smooth Scrolling

css
/* CSS smooth scroll */
html {
  scroll-behavior: smooth;
}
javascript
// JavaScript smooth scroll
document.querySelector('a[href^="#"]').addEventListener('click', (e) => {
  e.preventDefault();
  const target = document.querySelector(e.target.getAttribute('href'));
  target.scrollIntoView({ behavior: 'smooth' });
});

Styling Anchor Tags

CSS Pseudo-Classes

css
/* Default state */
a {
  color: blue;
  text-decoration: none;
}

/* Unvisited link */
a:link {
  color: blue;
}

/* Visited link */
a:visited {
  color: purple;
}

/* Mouse over */
a:hover {
  color: darkblue;
  text-decoration: underline;
}

/* Active/being clicked */
a:active {
  color: red;
}

/* Keyboard focus */
a:focus {
  outline: 2px solid orange;
}

Modern Link Styles

css
/* Remove underline */
a {
  text-decoration: none;
}

/* Underline on hover only */
a {
  text-decoration: none;
  border-bottom: 2px solid transparent;
  transition: border-color 0.3s;
}

a:hover {
  border-bottom-color: currentColor;
}

/* External link icon */
a[target="_blank"]::after {
  content: "";
  font-size: 0.8em;
}

Accessibility

Best Practices

html
<!-- Good: Descriptive text -->
<a href="/products">View our products</a>

<!-- Avoid: Generic text -->
<a href="/products">Click here</a>

<!-- Add context for screen readers -->
<a href="/delete" aria-label="Delete user account">
  Delete
</a>

<!-- Indicate external links -->
<a href="https://external.com" target="_blank">
  External Site
  <span class="sr-only">(opens in new tab)</span>
</a>

<!-- Skip navigation link -->
<a href="#main-content" class="skip-link">
  Skip to main content
</a>

React/Next.js Links

Next.js Link Component

jsx
import Link from 'next/link';

function Navigation() {
  return (
    <nav>
      {/* Client-side navigation */}
      <Link href="/about">About</Link>

      {/* With custom styling */}
      <Link href="/products" className="nav-link">
        Products
      </Link>

      {/* External link */}
      <Link href="https://external.com" target="_blank" rel="noopener">
        External
      </Link>

      {/* Programmatic navigation */}
      <Link href={{
        pathname: '/product/[id]',
        query: { id: '123' }
      }}>
        Product 123
      </Link>
    </nav>
  );
}

React Router Link

jsx
import { Link } from 'react-router-dom';

function Navigation() {
  return (
    <nav>
      <Link to="/">Home</Link>
      <Link to="/about">About</Link>
      <Link to="/contact">Contact</Link>
    </nav>
  );
}

JavaScript Interaction

Get Link Information

javascript
const link = document.querySelector('a');

// Get href
console.log(link.href); // Full URL
console.log(link.getAttribute('href')); // As written in HTML

// Get parts of URL
console.log(link.protocol); // "https:"
console.log(link.hostname); // "example.com"
console.log(link.pathname); // "/page"
console.log(link.hash); // "#section"

// Get link text
console.log(link.textContent);
console.log(link.innerText);

Modify Links

javascript
// Change href
link.href = 'https://newsite.com';

// Add attributes
link.target = '_blank';
link.rel = 'noopener noreferrer';

// Trigger click programmatically
link.click();

Prevent Default Behavior

javascript
document.querySelectorAll('a').forEach(link => {
  link.addEventListener('click', (e) => {
    e.preventDefault();
    // Custom behavior
    console.log('Link clicked:', link.href);
  });
});

Common Patterns

Active Navigation Link

javascript
// Highlight current page in navigation
const currentPath = window.location.pathname;
document.querySelectorAll('nav a').forEach(link => {
  if (link.pathname === currentPath) {
    link.classList.add('active');
  }
});

Confirm Before Navigation

javascript
document.querySelectorAll('a.dangerous').forEach(link => {
  link.addEventListener('click', (e) => {
    if (!confirm('Are you sure you want to leave?')) {
      e.preventDefault();
    }
  });
});

Track Outbound Links

javascript
document.querySelectorAll('a[target="_blank"]').forEach(link => {
  link.addEventListener('click', () => {
    // Analytics tracking
    gtag('event', 'outbound_link', {
      url: link.href
    });
  });
});

Security Considerations

Always use rel="noopener" with target="_blank"

html
<!-- Prevents reverse tabnapping vulnerability -->
<a href="https://external.com" target="_blank" rel="noopener noreferrer">
  External Link
</a>

Validate User-Generated Links

javascript
// Sanitize user-provided URLs
function sanitizeUrl(url) {
  const allowed = ['http:', 'https:', 'mailto:', 'tel:'];
  try {
    const parsed = new URL(url);
    return allowed.includes(parsed.protocol) ? url : '#';
  } catch {
    return '#';
  }
}

Best Practices

  • Use descriptive link text (avoid "click here")
  • Include rel="noopener noreferrer" for external links with target="_blank"
  • Make links keyboard accessible
  • Ensure sufficient color contrast
  • Show focus states for keyboard navigation
  • Indicate external links visually
  • Use appropriate protocols (https, mailto, tel)
  • Test on mobile devices (touch targets)
  • Don't use JavaScript protocols (javascript:)

Learn More