HTML <link> Tag: Explained with Examples

The HTML <link> tag is a self-closing tag used to link external resources such as stylesheets, icons, and other web pages to an HTML document. It is commonly used to connect a web page with external resources to control its presentation and behavior. In this blog post, we'll explore the <link> tag in detail, covering its attributes, use cases, and examples.

Syntax

link to this section

The <link> tag has the following syntax:

<link rel="stylesheet" href="styles.css"> 

Attributes

link to this section
  • rel : Specifies the relationship between the current document and the linked resource. Common values include:
    • stylesheet : Specifies the linked resource as a stylesheet.
    • icon : Specifies the linked resource as an icon.
    • preload : Specifies that the linked resource should be preloaded.
  • href : Specifies the URL of the linked resource.
  • type : Specifies the MIME type of the linked resource.
  • media : Specifies the media type of the linked resource.

Example Use Cases

link to this section

Linking Stylesheets

<link rel="stylesheet" href="styles.css"> 

Linking Icons

<link rel="icon" href="favicon.ico" type="image/x-icon"> 

Preloading Resources

<link rel="preload" href="font.woff2" as="font" type="font/woff2"> 

Best Practices

link to this section
  • Always use the rel attribute to specify the relationship of the linked resource.
  • Use the href attribute to specify the URL of the linked resource.
  • Consider using the type attribute to specify the MIME type of the linked resource for better browser compatibility.
  • Use the media attribute to specify the media type of the linked resource, especially for stylesheets.

Conclusion

link to this section

The HTML <link> tag is a versatile element that allows web developers to link external resources to HTML documents. Whether it's stylesheets, icons, or preloaded resources, the <link> tag provides a convenient way to enhance the presentation and behavior of web pages. By understanding its attributes and best practices, developers can effectively leverage the <link> tag to optimize their web development projects.