The link
element creates a relationship between an HTML document and
an external resource, a CSS stylesheet or a Javascript file.
link
element has local Attributes: href, rel, hreflang, media, type, sizes
.
text/css
or image/x-icon
.
The sizes
attribute has been added in HTML5 and the attributes
charset
, rev
and target
are obsolete in HTML5.
The rel
attribute value determines how the browser deals with the link element.
The following list shows common values for the rel
attribute.
To demonstrate the link
element,
I have created a stylesheet called styles.css
, which has the following content.
a { background-color: grey; color: red; padding: 0.5em; }
To apply this stylesheet, we can use the link element as shown in the following code.
<!DOCTYPE HTML> <html> <head> <link rel="stylesheet" type="text/css" href="styles.css" /> </head> <body> <p>This is a test.</p> <a href="http://java2s.com">Visit java2s.com</a> </body> </html>
You can use multiple link
elements to load multiple external resources.
An external stylesheet can be reused in multiple documents.
You can ask the browser to pre-fetch a resource.
The following code shows the use of the link
element to specify prefetching.
<!DOCTYPE HTML> <html> <head> <link rel="prefetch" href="/page2.html" /> </head> <body> <p>This is a test.</p> <a href="http://java2s.com">Visit java2s.com</a> <a href="page2.html">Page 2</a> </body> </html>
The code above set the rel
attribute to prefetch
and specified that an HTML page, page2.html
, be loaded in the expectation
that the user will use this page.