Understanding and Using the HTML `<link>` Element: Linking External Resources
Learn how to use the HTML `<link>` element to link external resources, such as stylesheets, to your HTML documents. This tutorial explains key attributes (`rel`, `href`), best practices, and the importance of `<link>` for organizing and enhancing website functionality.
Understanding and Using the HTML `<link>` Element
What is the `<link>` Element?
The HTML `<link>` element is used to establish relationships between the current HTML document and external resources. It doesn't display anything on the page itself; its purpose is to link to external files, improving both code organization and website functionality. The most common use is to link to external stylesheets (CSS files) to separate your styles from your HTML. The `<link>` tag is an empty tag (it doesn't have a closing tag), and it requires the `rel` attribute to specify the relationship and the `href` attribute to specify the URL of the linked resource. The `href` attribute specifies the URL (or path) of the linked resource.
Key Attributes of the `<link>` Element
The most important attributes for the `<link>` tag are:
Attribute | Value | Description |
---|---|---|
crossorigin |
anonymous , use-credentials |
Controls how the browser handles cross-origin requests for the linked resource. |
href |
URL | The URL of the linked resource (required). |
hreflang |
Language code | Specifies the language of the linked document. |
media |
Media query | Specifies the media type (screen size, etc.) for which the linked resource is intended. |
referrerpolicy |
Value (e.g., `no-referrer`) | Controls referrer information sent with the request. |
rel |
Relationship (e.g., `stylesheet`, `icon`, `preconnect`, `dns-prefetch`, etc.) | Specifies the relationship between the current document and the linked resource (required). |
sizes |
Size | Specifies the size of the linked resource (used with `rel="icon"`). |
title |
Text | Provides a title for the linked stylesheet (for selecting between multiple stylesheets). |
type |
MIME type | Specifies the MIME type of the linked document (e.g., `text/css` for stylesheets). |
The `<link>` element also supports standard HTML global and event attributes. However, it’s important to note that event attributes are not typically used with the `<link>` element.
Example: Linking to a Stylesheet
Example: Linking to a Stylesheet
<link rel="stylesheet" href="styles.css">
This line links an external stylesheet named `styles.css` to the HTML document. The browser will download and apply the styles defined in this stylesheet to elements on the page.
Browser Support for `<link>`
The `<link>` element is supported by all major modern browsers.
Browser | Support |
---|---|
Chrome | Yes |
Edge | Yes |
Firefox | Yes |
Opera | Yes |
Safari | Yes |