HTML <link> Tag

The HTML <link> tag represents a link to an external resource.

The <link> element is often used to link to an external style sheet, but it's usage is not restricted to this. For example, it can also be used for defining a relational framework for a site's navigation, and it can also provide useful information to search engines.

The basic tag is written like this <link rel=""> with the rel attribute providing the relationship between the HTML document and the destination resource. For example rel="stylesheet" indicates that the external resource is a style sheet for the current document.

Similarly to the <a> tag, the <link> tag creates a hyperlink. However, the hyperlink established with the <link> tag is not normally as apparent to the user as those created with the <a> tag. Also, if the <link> element has the rel attribute defined, the element must be located in the document's <head>.

Note that the W3C HTML5 recommendation states that A link element must have a rel attribute.. However, the WHATWG HTML Living Standard states A link element must have a rel attribute or an itemprop attribute, but not both.

Also note that hyperlinks created with the <link> element and its rel attribute apply to the whole page. This contrasts with the rel attribute of <a> and <area> elements, which indicates the type of a link whose context is given by the link's location within the document.

Example

The following example shows the <link> element in action. You can modify the code (on the left) and click "Refresh" to see your changes take effect (on the right).

Source CodeResult

Attributes

The <link> tag accepts the following attributes. Try adding some to the above example to see how it affects the display/behavior of the element.

Attributes Specific to the <link> Element

AttributeDescription
hrefSpecifies the URL of the resource document.
crossoriginThis attribute is a CORS settings attribute. CORS stands for Cross-Origin Resource Sharing. The purpose of the crossorigin attribute is to allow you to configure the CORS requests for the element's fetched data. The values for the crossorigin attribute are enumerated.

Possible values:

ValueDescription
anonymousCross-origin CORS requests for the element will not have the credentials flag set. In other words, there will be no exchange of user credentials via cookies, client-side SSL certificates or HTTP authentication.
use-credentialsCross-origin CORS requests for the element will have the credentials flag set.

If this attribute is not specified, CORS is not used at all.

An invalid keyword and an empty string will be handled as the anonymous value.

relDescribes the relationship between the current document and the destination URI. Multiple values can be provided, separated by a space.

Possible values:

ValueDescription
alternateGives alternate representations of the current document. For example, here is sample code (taken from the HTML5 specification) for giving the syndication feed for the current page: <link rel="alternate" type="application/atom+xml" href="data.xml">
canonicalGives the preferred URL for the current document.
authorGives a link to the current document's author.
dns-prefetchSpecifies that the user agent should preemptively perform DNS resolution for the target resource's origin.
helpProvides a link to context-sensitive help.
iconImports an icon to represent the current document.
modulepreloadSpecifies that the user agent must preemptively fetch the module script and store it in the document's module map for later evaluation. Optionally, the module's dependencies can be fetched as well.
licenseIndicates that the main content of the current document is covered by the copyright license described by the referenced document.
nextIndicates that the current document is a part of a series, and that the next document in the series is the referenced document.
pingbackGives the address of the pingback server that handles pingbacks to the current document.
preconnectSpecifies that the user agent should preemptively connect to the target resource's origin.
prefetchSpecifies that the user agent should preemptively fetch and cache the target resource as it is likely to be required for a followup navigation.
preloadSpecifies that the user agent must preemptively fetch and cache the target resource for current navigation according to the potential destination given by the as attribute (and the priority associated with the corresponding destination).
prerenderSpecifies that the user agent should preemptively fetch the target resource and process it in a way that helps deliver a faster response in the future.
prevIndicates that the current document is a part of a series, and that the previous document in the series is the referenced document.
searchGives a link to a resource that can be used to search through the current document and its related pages.
stylesheetImports an external stylesheet.
revReverse link relationship of the destination resource to this document (or subsection/topic).
mediaSpecifies which media the target URL uses. Only to be used when the href attribute is present.

Value:

[The value must be a valid media query. The default value is all].

nonceRepresents a cryptographic nonce ("number used once") which can be used by Content Security Policy to determine whether or not an external resource specified by the link will be loaded and applied to the document. The value is text.
hreflangLanguage code of the destination URL. Purely advisory. The value must be a valid RFC 3066 language code.
typeThe MIME type of content at the link destination. Purely advisory.
referrerpolicyReferrer policy for fetches initiated by the element.
sizesSpecifies the sizes of icons for visual media. Can be used for favicons. Multiple values can be provided, as long as they're separated by a space.

Examples:

  • sizes="16x16" (1 size)
  • sizes="16x16 32x32 64x64" (3 different sizes)
  • sizes="any" (any size)

Global Attributes

The <link> tag accepts the following global attributes. These attributes are standard across all HTML 5 tags.

Attribute Description
accesskey Specifies a shortcut key that can be used to access the element.

Possible values.

[Any string of characters. This string of characters specifies the key/s the user needs to use in order to access the element.]

autocapitalize Specifies whether and how text input is automatically capitalized as it is entered/edited by the user.

Possible values:

ValueDescription
offNo autocapitalization is applied (all letters default to lowercase).
noneSame as off.
onThe first letter of each sentence defaults to a capital letter; all other letters default to lowercase.
sentencesSame as on.
wordsThe first letter of each word defaults to a capital letter; all other letters default to lowercase.
charactersAll letters should default to uppercase.
class Document wide identifier. Used to refer to a class specified in the style sheet. The value should be the name of the class you wish to use.
contenteditable Sets whether the user can edit the content or not.

Possible values:

  • true
  • false
contextmenu Sets a context menu for an element. The value must be the ID of a menu element in the DOM
data-*

Custom data attribute. The asterisk (*) is a wildcard character, which means that you replace this character with your own string. For example, data-length, data-code, etc.

Custom data attributes are intended to store custom data, state, annotations, and similar, private to the page or application, for which there are no more appropriate attributes or elements.

dir Specifies the direction of the text.

Possible values:

ValueDescription
ltrSpecifies that the text should read left to right.
rtlSpecifies that the text should read right to left.
autoSpecifies that the text direction should be determined programatically using the contents of the element.
draggable Specifies whether the user is allowed to drag the element or not.

Possible values:

ValueDescription
trueSpecifies that the element is draggable.
falseSpecifies that the element is not draggable.
autoUses the default behavior of the user agent/browser. This is the default value.
dropzone Specifies what should happen when the user "drops" an element (i.e. after dragging it) onto the current element.

Must be an unordered set of unique space-separated tokens that are ASCII case-insensitive.

Possible values:

ValueDescription
copyResults in a copy of the dragged data. Default value.
moveResults in the data being moved to the new location.
linkResults in a link to the original data.
Any keyword with eight characters or more, beginning with the an ASCII case-insensitive match for the string "string:"Specifies that items with the drag data item kind Plain Unicode string and the drag data item type string set to a value that matches the remainder of the keyword are accepted.
Any keyword with six characters or more, beginning with an ASCII case-insensitive match for the string "file:"Allows you to specify which file types can be processed (i.e. copied, moved or linked) in this dropzone. Example: dropzone="copy file:image/png file:image/gif file:image/jpeg"

Note that this attribute must not have more than one of the three feedback values (copy, move, and link) specified. If none are specified, the copy value is implied.

hidden

Indicates that the element is not yet, or is no longer, relevant. The browser/user agent does not display elements that have the hidden attribute present.

This is a boolean attribute. If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace (i.e. either hidden or hidden="hidden").

Possible values:

  • [Empty string]
  • hidden
id Document wide identifier. Used with CSS and JavaScript. The value should be the name of the id you wish to use.
inert Boolean attribute that indicates that the element is to be made inert. This means that the browser/user agent acts as though the element is not there, even though it may still display the element.

For example, a block of text that has been marked with the inert attribute may not be searchable when the user attempts a browser text search (eg, commonly called "Find in page" or similar). The text may not be able to be targetted for user interaction events (such as mouseover etc), and the user may not be able to select the block of text.

This is a boolean attribute. If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace (i.e. either inert or inert="inert").

Possible values:

  • [Empty string]
  • inert
itemid Provides a global identifier for an "item". The itemid attribute is optional, however if it is provided, it must have a value that is a valid URL potentially surrounded by spaces.

The itemid attribute can only be present in elements that include both the itemscope and the itemtype attributes, as long as the itemtype attribute specifies a vocabulary that supports global identifiers for items, as defined by that vocabulary's specification.

itemprop Provides one or more properties to one or more "items".

Although the itemprop attribute is optional and can be used on any HTML element, if used it must have a value that is an unordered set of unique space-separated tokens that are case-sensitive, representing the names of the name-value pairs that it adds. The attribute's value must have at least one token. According to the HTML5 specification, each token must be one of the following:

  • A valid URL that is an absolute URL, or
  • If the item is a typed item: a "defined property name" allowed in this situation according to the specification that defines the relevant types for the item, or
  • If the item is not a typed item: a string that contains no U+002E FULL STOP characters (.) and no U+003A COLON characters (:).

Also, Specifications that introduce defined property names that are not absolute URLs must ensure all such property names contain no U+002E FULL STOP characters (.), no U+003A COLON characters (:), and no space characters.

itemref

Used in conjunction with the itemscope attribute, the itemref attribute provides a list of additional elements to crawl to find the name-value pairs of the "item". Although the itemref attribute is optional, if specified, it must have a value that is an unordered set of unique space-separated tokens that are case-sensitive, consisting of IDs of elements in the same home subtree. Also, the itemref can only be used on elements that also have the itemscope attribute present.

itemscope

HTML5 elements that have the itemscope attribute create a name-value pair called an "item". Elements with an itemscope attribute may also have an itemtype attribute specified, to give the item types of the item.

This is a boolean attribute. If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace (i.e. either itemscope or itemscope="itemscope").

Possible values:

  • [Empty string]
  • itemscope
itemtype Provides an item type for elements containing the itemscope attribute. The itemtype attribute is optional however, if it is specified, it must have a value that is an unordered set of unique space-separated tokens that are case-sensitive, each of which is a valid URL that is an absolute URL, and all of which are defined to use the same vocabulary. The attribute's value must have at least one token.

The itemtype attribute must only be present in elements that include the itemscope attribute.

lang Sets the language code to be used.

Possible values:

[Must be a valid RFC 3066 language code, or an empty string.]

spellcheck Specifies whether the element should have its spelling checked.
ValueDescription
[Empty string]The element should have its spelling checked.
trueThe element should have its spelling checked.
falseThe element should not have its spelling checked.

If this attribute is missing, the element will use the default behavior, possibly based on the parent's own spellcheck state.

slot

Assigns a slot to an element: an element with a slot attribute is assigned to the slot created by the slot element whose name attribute's value matches that slot attribute's value — but only if that slot element finds itself in the shadow tree whose root's host has the corresponding slot attribute value.

style Specifies inline styles for the element. The value should be the style definition you wish to use.
tabindex Helps determine the tabbing order (when the user 'tabs' through the elements on the page).

Possible values:

[Any valid integer. For example, 0, 1, 2, 3, ...etc]

title Specifies a title to associate with the element. Many browsers will display this when the cursor hovers over the element (similar to a "tool tip").

Possible values:

[Any text to be displayed as a "tool tip".]

translate Specifies whether the element's attribute values and the values of its Text node children are to be translated when the page is localized, or whether to leave them unchanged.

The translate attribute is an enumerated attribute and may contain the following possible values:

  • [Empty String]
  • yes
  • no

If the translate attribute is provided, but its value is missing or is invalid, the element will inherit its value from its parent element.

Event Handler Content Attributes

An event handler content attribute is an attribute for a specific event handler.

Event handlers are commonly used to extend the functionality of an HTML element. By using event handler content attributes, you can tell the browser to run a specific script and when to run it. For example, by using onclick="", you tell the browser to run a script whenever someone clicks on the element.

The HTML specification includes the following event handler content attributes. Most can be used on all HTML elements, but there are exceptions, as outlined below.

Event Handlers for All HTML Elements & document & window Objects

The following table lists the event handlers supported by all HTML elements, as both event handler content attributes and event handler IDL attributes; and supported by all Document and Window objects, as event handler IDL attributes.

Attribute Description
onabort Invoked when an event has been aborted. For example, the browser stops fetching media data before it is completely downloaded.
onauxclick auxclick event handler.
oncancel cancel event handler.
oncanplay Invoked when the browser/user agent can start playing media, but hasn't yet, due to buffering. In other words, if playback were to begin now, it wouldn't play right to the end (due to the current playback rate) - it would need to pause during playback in order to load the rest of the media.
oncanplaythrough The browser/user agent estimates that if playback were to begin now, the media resource could be rendered at the current playback rate all the way to its end without having to stop for further buffering.
onchange User has changed the object, then attempts to leave that field (i.e. clicks elsewhere).
onclick Invoked when the user clicked on the object.
onclose close event handler.
oncontextmenu Invoked when a context menu has been triggered.
oncuechange cuechange event handler.
ondblclick Invoked when the user clicked twice on the object.
ondrag Invoked when an element is being dragged.
ondragend Invoked when an element has stopped being dragged.
ondragenter Invoked when an element has been dragged to a drop target.
ondragexit dragexit event handler.
ondragleave Invoked when an element leaves a valid drop target.
ondragover Invoked when an element is being dragged over a valid drop target.
ondragstart Invoked when a drag operation has started.
ondrop Invoked when an element is being dropped.
ondurationchange Invoked when the length of the media is changed (i.e. the duration attribute has just been updated).
onemptied Invoked when a media resource element suddenly becomes empty (for example, due to a network error).
onended Invoked when the media has reached the end.
onformdata formdata event handler.
oninput input event handler.
oninvalid invalid event handler.
onkeydown Invoked when a key was pressed over an element.
onkeypress Invoked when a key was pressed over an element then released.
onkeyup Invoked when a key was released over an element.
onloadeddata Invoked when the browser/user agent can render the media data at the current playback position for the first time.
onloadedmetadata Invoked when the browser/user agent has just determined the duration and dimensions of the media resource.
onloadstart Invoked when the browser/user agent has started loading the media resource.
onmousedown The cursor moved over the object and mouse/pointing device was pressed down.
onmouseenter mouseenter event handler.
onmouseleave mouseleave event handler.
onmousemove The cursor moved while hovering over an object.
onmouseout The cursor moved off the object
onmouseover The cursor moved over the object (i.e. user hovers the mouse over the object).
onmouseup The mouse/pointing device was released after being pressed down.
onpause Invoked when the media resource has been paused.
onplay Invoked when the media resource starts playback.
onplaying Playback has begun.
onprogress The browser/user agent is fetching media data the.
onratechange Invoked when the playback rate has changed (i.e. either the defaultPlaybackRate or the playbackRate has just been updated).
onreset reset event handler.
onsecuritypolicyviolation securitypolicyviolation event handler.
onseeked Invoked when the seeking IDL attribute changed to false (i.e. the seeking attribute is no longer true)
onseeking Invoked when the seeking IDL attribute changed to true and the seek operation is taking long enough that the user agent has time to fire the event.
onselect Invoked when some or all of the contents of an object is selected. For example, the user selected some text within a text field.
onslotchange slotchange event handler.
onstalled Invoked when the browser/user agent is trying to fetch media data but the data has stalled (i.e. the data has stopped coming).
onsubmit User submitted a form.
onsuspend The browser/user agent is (intentionally) not currently fetching media data, but has not yet downloaded the entire media resource (i.e. it has suspended the download).
ontimeupdate Invoked when the media's current playback position changed.
ontoggle toggle event handler.
onvolumechange Invoked when either the volume attribute or the muted attribute has changed.
onwaiting The next frame of the media is not yet available (but the browser/user agent expects it to become available).
onwebkitanimationend webkitanimationend event handler.
onwebkitanimationiteration webkitAnimationIteration event handler.
onwebkitanimationstart webkitAnimationStart event handler.
onwebkittransitionend webkitTransitionEnd event handler.
onwheel wheel event handler.

The following table lists the event handlers (and their corresponding event handler event types) supported by all HTML elements other than body and frameset elements, as both event handler content attributes and event handler IDL attributes; supported by all Document objects, as event handler IDL attributes; and supported by all Window objects, as event handler IDL attributes on the Window objects themselves, and with corresponding event handler content attributes and event handler IDL attributes exposed on all body and frameset elements that are owned by that Window object's associated Document.

Attribute Description
onblur User has left the focus of the element.
onerror Invoked when an error occurs while the Window object is being loaded. Also handler for script error notifications.
onfocus Invoked when the focus is on the element.
onload The element has loaded.
onresize The viewport has been resized.
onscroll scroll event handler. Invoked when the element's scrollbar is being scrolled.

The following table lists the event handlers supported by Window objects, as event handler IDL attributes on the Window objects themselves, and with corresponding event handler content attributes and event handler IDL attributes exposed on all body and frameset elements that are owned by that Window object's associated Document.

Attribute Description
onafterprint afterprint event handler
onbeforeprint beforeprint event handler
onbeforeunload beforeunload event handler
onhashchange hashchange event handler. The hashchange event is fired when navigating to a session history entry whose URL differs from that of the previous one only in the fragment identifier.
onlanguagechange languagechange event handler.
onmessage message event handler.
onmessageerror messageerror event handler.
onoffline offline event handler.
ononline online event handler.
onpagehide pagehide event handler. The pagehide event is fired when traversing from a session history entry.
onpageshow pageshow event handler. The pageshow event is fired when traversing to a session history entry.
onpopstate popstate event handler. The popstate event is fired when navigating to a session history entry that represents a state object.
onrejectionhandled rejectionhandled event handler.
onstorage storage event handler.
onunhandledrejection unhandledrejection event handler.
onunload unload event handler.

The following are the event handlers supported by all HTML elements, as both event handler content attributes and event handler IDL attributes; and supported by all Document objects, as event handler IDL attributes:

Attribute Description
oncut cut event handler.
oncopy copy event handler.
onpaste paste event handler.

The following event handler is supported on Document objects as an event handler IDL attribute.

Attribute Description
onreadystatechange readystatechange event handler.

See the full list of HTML tags