HTML <link> link tag


The <link> tag in HTML is used to define the relationship between the current document and an external resource. It is most commonly used to link to external stylesheets (CSS) or other linked resources like icons and prefetch hints.

Attributes of the <link> Tag:

  • rel (required): Defines the relationship between the document and the linked resource. For example, rel="stylesheet" is used for linking stylesheets.
  • href (required): Specifies the URL of the external resource. For stylesheets, this is the location of the CSS file.
  • type: Specifies the MIME type of the linked document (commonly used for stylesheets or prefetching resources).
  • media: Specifies the media type for which the resource is optimized, such as media="screen" or media="print".

Common Uses of <link>:

  1. Linking CSS Stylesheets: This is the most common use case for the <link> tag, where external CSS files are linked to the HTML document.
<link rel="stylesheet" href="styles.css">

This links an external CSS file (styles.css) to the HTML document.

  1. Favicon (Website Icon): It can also be used to link a favicon (the small icon displayed on the browser tab for a website).
<link rel="icon" href="favicon.ico" type="image/x-icon">
  1. Prefetching Resources: You can use the <link> tag for prefetching or preloading certain resources, improving performance.
<link rel="preload" href="image.jpg" as="image">

Example of <link> in a Document:

<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>My Website</title> <link rel="stylesheet" href="styles.css"> <link rel="icon" href="favicon.ico" type="image/x-icon"> </head> <body> <h1>Welcome to My Website</h1> </body> </html>

Key Points:

  • The <link> tag is a self-closing tag, meaning it does not have a closing counterpart (like <link></link>).
  • It must be placed inside the <head> section of the HTML document.
  • It does not display any content; it merely links external resources.

In summary, the <link> tag is vital for adding external resources to an HTML document, most commonly for styling and adding website icons.