Html-элемент link

HTML Tags

<!—><!DOCTYPE><a><abbr><acronym><address><applet><area><article><aside><audio><b><base><basefont><bdi><bdo><big><blockquote><body><br><button><canvas><caption><center><cite><code><col><colgroup><data><datalist><dd><del><details><dfn><dialog><dir><div><dl><dt><em><embed><fieldset><figcaption><figure><font><footer><form><frame><frameset><h1> — <h6><head><header><hr><html><i><iframe><img><input><ins><kbd><label><legend><li><link><main><map><mark><meta><meter><nav><noframes><noscript><object><ol><optgroup><option><output><p><param><picture><pre><progress><q><rp><rt><ruby><s><samp><script><section><select><small><source><span><strike><strong><style><sub><summary><sup><svg><table><tbody><td><template><textarea><tfoot><th><thead><time><title><tr><track><tt><u><ul><var><video>

Атрибуты¶

Путь к связываемому файлу.
Определяет устройство, для которого следует применять стилевое оформление.
Определяет отношения между текущим документом и файлом, на который делается ссылка.
Указывает размер иконок для визуального отображения.
MIME-тип данных подключаемого файла.

Также для этого элемента доступны универсальные атрибуты.

href

Путь к файлу, на который делается ссылка.

Синтаксис

Значения

В качестве значения принимается полный или относительный путь к файлу.

Значение по умолчанию

Нет.

media

Определяет устройство, для которого следует применять стилевое оформление. Это позволяет сделать разный стиль для отображения документа на экране монитора и при его печати. Допускается писать несколько значений через запятую.

Синтаксис

Значения

Все устройства.
Печатающее устройство вроде принтера.
Экран монитора.
Речевые синтезаторы, а также программы для воспроизведения текста вслух. Сюда же входят речевые браузеры.

В HTML5 в качестве значений могут быть указаны медиа-запросы.

Значение по умолчанию

rel

Атрибут определяет отношения между текущим документом и файлом, на который делается ссылка. Это необходимо, чтобы браузер знал, как использовать подключаемый документ.

Синтаксис

Значения

Альтернативный тип, используется, к примеру, для указания ссылки на файл в формате XML для описания ленты новостей, анонсов статей.
Указывает ссылку на автора текущего документа или статьи.
Указывает ссылку на контекстно-зависимую справку.
Адрес картинки, которая символизирует текущий документ или сайт.
Сообщает, что основное содержание текущего документа распространяется по лицензии, описанной в указанном документе.
Сообщает, что текущий документ является частью связанных между собой документов, а ссылка указывает на следующий документ.
Указывает на предварительно кэшированный ресурс текущей страницы или сайта целиком.
Сообщает, что текущий документ является частью связанных между собой документов, а ссылка указывает на предыдущий документ.
Указывает ссылку на ресурс, который применяется для поиска по документу или сайту.
Определяет, что подключаемый файл хранит таблицу стилей (CSS).

Значение по умолчанию

Нет.

sizes

Указывает размер иконок для визуального отображения. Сама иконка может применяться браузером для отображения в адресной строке, при сохранении в избранное, а также поисковыми системами для придания наглядности результатам поиска (именно так поступает Яндекс).

Синтаксис

Значения

Вначале указывается ширина иконки в пикселах без указания единиц (например, 16), затем пишется латинская буква x в верхнем (X) или нижнем регистре (x), после чего идёт высота иконки. Если в файле хранится сразу несколько иконок, можно задавать их размеры через пробел. Ключевое слово указывает, что иконка может масштабироваться в любой размер, к примеру, если она хранится в векторном формате SVG.

Значение по умолчанию

Нет.

type

Сообщает браузеру, какой MIME-тип данных используется для внешнего документа. Как правило, применяется для того, чтобы указать, что подключаемый файл содержит CSS.

Синтаксис

Значения

Имя MIME-типа в любом регистре. Для подключаемых таблиц связанных стилей применяется тип .

Значение по умолчанию

Setting the Targets for Links

The attribute tells the browser where to open the linked document. There are four defined targets, and each target name starts with an underscore() character:

  • — Opens the linked document in a new window or tab.
  • — Opens the linked document in the parent window.
  • — Opens the linked document in the same window or tab as the source document. This is the default, hence it is not necessary to explicitly specify this value.
  • — Opens the linked document in the full browser window.

Try out the following example to understand how the link’s target basically works:

Example

Try this code

Tip: If your web page is placed inside an iframe, you can use the on the links to break out of the iframe and show the target page in full browser window.

CSS Tutorial

CSS HOMECSS IntroductionCSS SyntaxCSS SelectorsCSS How ToCSS CommentsCSS Colors
Colors
RGB
HEX
HSL

CSS Backgrounds
Background Color
Background Image
Background Repeat
Background Attachment
Background Shorthand

CSS Borders
Borders
Border Width
Border Color
Border Sides
Border Shorthand
Rounded Borders

CSS Margins
Margins
Margin Collapse

CSS PaddingCSS Height/WidthCSS Box ModelCSS Outline
Outline
Outline Width
Outline Color
Outline Shorthand
Outline Offset

CSS Text
Text Color
Text Alignment
Text Decoration
Text Transformation
Text Spacing
Text Shadow

CSS Fonts
Font Family
Font Web Safe
Font Fallbacks
Font Style
Font Size
Font Google
Font Pairings
Font Shorthand

CSS IconsCSS LinksCSS ListsCSS Tables
Table Borders
Table Size
Table Alignment
Table Style
Table Responsive

CSS DisplayCSS Max-widthCSS PositionCSS OverflowCSS Float
Float
Clear
Float Examples

CSS Inline-blockCSS AlignCSS CombinatorsCSS Pseudo-classCSS Pseudo-elementCSS OpacityCSS Navigation Bar
Navbar
Vertical Navbar
Horizontal Navbar

CSS DropdownsCSS Image GalleryCSS Image SpritesCSS Attr SelectorsCSS FormsCSS CountersCSS Website LayoutCSS UnitsCSS SpecificityCSS !important

The target Attribute

We have used target attribute in our previous example. This attribute is used to specify the location where linked document is opened. Following are the possible options −

Sr.No Option & Description
1

_blank

Opens the linked document in a new window or tab.

2

_self

Opens the linked document in the same frame.

3

_parent

Opens the linked document in the parent frame.

4

_top

Opens the linked document in the full body of the window.

5

targetframe

Opens the linked document in a named targetframe.

Example

Try following example to understand basic difference in few options given for target attribute.

<!DOCTYPE html>
<html>

   <head>
      <title>Hyperlink Example</title>
      <base href = "https://www.tutorialspoint.com/">
   </head>
	
   <body>
      <p>Click any of the following links</p>
      <a href = "/html/index.htm" target = "_blank">Opens in New</a> |
      <a href = "/html/index.htm" target = "_self">Opens in Self</a> |
      <a href = "/html/index.htm" target = "_parent">Opens in Parent</a> |
      <a href = "/html/index.htm" target = "_top">Opens in Body</a>
   </body>

</html>

This will produce the following result, where you can click on different links to understand the difference between various options given for target attribute.

CSS Advanced

CSS Rounded CornersCSS Border ImagesCSS BackgroundsCSS ColorsCSS Color KeywordsCSS Gradients
Linear Gradients
Radial Gradients

CSS Shadows
Shadow Effects
Box Shadow

CSS Text EffectsCSS Web FontsCSS 2D TransformsCSS 3D TransformsCSS TransitionsCSS AnimationsCSS TooltipsCSS Style ImagesCSS Image ReflectionCSS object-fitCSS object-positionCSS ButtonsCSS PaginationCSS Multiple ColumnsCSS User InterfaceCSS Variables
The var() Function
Overriding Variables
Variables and JavaScript
Variables in Media Queries

CSS Box SizingCSS Media QueriesCSS MQ ExamplesCSS Flexbox
CSS Flexbox
CSS Flex Container
CSS Flex Items
CSS Flex Responsive

Link Targets

You can nominate whether to open the URL in a new window or the current window. You do this with the attribute. For example, opens the URL in a new window.

The target attribute can have the following possible values:

Opens the URL in a new browser window.
Loads the URL in the current browser window.
Loads the URL into the parent frame (still within the current browser window). This is only applicable when using frames.
Loads the URL in the current browser window, but cancelling out any frames. Therefore, if frames were being used, they aren’t any longer.

Example:

<a href=»https://www.quackit.com» target=»_blank»>Quackit</a>

Атрибуты HTML-элемента link

HREF

Наличие этого атрибута является обязательным. Если он отсутствует или имеет значение, которое не является допустимым URI, элемент не определяет ссылку.

Пример

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

CROSSORIGIN

Указывает, должен ли запрос к внешнему серверу предоставлять учетные данные CORS или нет. Допустимы два значения (без учета регистра):

  • anonymous: CORS запросы к элементу будут содержать установленный флаг «omit credentials«;
  • use-credentials: CORS запросы к элементу не будут содержать установленный флаг «omit credentials«.

Пример

<link rel="icon" href="http://www.otherserver.com/icons/default.png" crossorigin="anonymous">

REL

Атрибут HTML link rel содержит разделенный пробелами список типов ссылок, указывающий, какое значение связанный ссылкой ресурс имеет для документа (содержащего ссылку).

Элемент link должен содержать либо атрибут rel, либо атрибут itemprop, но не оба сразу. Атрибут href также является обязательным.

Пример

<link rel="prev" href="article1.html"> 
<link rel="next" href="article3.html"> 
<link rel="license" href="copyright.html"> 
<link rel="alternate" href="spanish-version.html" hreflang="es">

MEDIA

Список медиа-запросов с указанием типов медиа (и их характеристик), для которых предназначен связанный ссылкой ресурс. Например, документ или ресурс может быть оптимизирован для печати (меньше цветов, изображений и фоновых тонов), под мобильные устройства или обычные экраны. Значение по умолчанию -«all«.

Пример

<link rel="alternate" href="printer-version.html" media="print">

HREFLANG

Этот HTML link tag указывает язык, который будет использоваться в связанном ссылкой ресурсе (указан в атрибуте HREF).

Пример

<link rel="alternate" hreflang="es" href="spanish-version.html">

TYPE

Тип контента (или Internet Media Type), который должен содержать связанный ресурс.

Пример

<link rel="icon" href="icon.png" type="image/png"> 
<link rel="next" href="article2.html" type="text/html">

SIZES

Разделенный пробелами список с размерами иконки ссылки. Каждый размер может состоять из двух целых чисел, разделенных буквой «х«, или из специального ключевого слова «any«, представляющего все возможные размеры. Каждое значение чувствительно к регистру.

Этот атрибут тега link в HTML должен объявляться только, когда присутствует атрибут rel и он имеет значение «icon«. Иначе ситуации его использование является недействительным.

Пример

<link rel="icon" href="icon.ico" sizes="64x64 32x32 16x16"> <link rel="icon" href="icon.svg" sizes="any">

CHARSET

Кодировка символов целевого ресурса. Этот атрибут является устаревшим и в HTML5 уже не используется. Вместо него разработчикам рекомендуется использовать HTTP-заголовки Content-Type, чтобы предоставить информацию о наборах символов в документах и других ресурсах.

Пример

<link rel="next" href="article2.html" charset="utf-8">

REV

Значение текущего документа (содержащего ссылку) для связанного ссылкой ресурса.

Этот атрибут HTML link tag является устаревшим и в HTML5 уже не используется. Разработчикам рекомендуется заменить его атрибутом rel.

Пример

<link rev="index" href="article1.html"> 
<link rev="index" href="article2.html"> 
<link rev="index" href="article3.html">

Linking Documents

A link is specified using HTML tag <a>. This tag is called anchor tag and anything between the opening <a> tag and the closing </a> tag becomes part of the link and a user can click that part to reach to the linked document. Following is the simple syntax to use <a> tag.

<a href = "Document URL" ... attributes-list>Link Text</a> 

Example

Let’s try following example which links http://www.tutorialspoint.com at your page −

<!DOCTYPE html>
<html>
   
   <head>
      <title>Hyperlink Example</title>
   </head>
	
   <body>
      <p>Click following link</p>
      <a href = "https://www.tutorialspoint.com" target = "_self">Tutorials Point</a>
   </body>
	
</html>

This will produce the following result, where you can click on the link generated to reach to the home page of Tutorials Point (in this example).

External CSS

An external style sheet is used to define the style for many HTML pages.

To use an external style sheet, add a link to it in the section of each HTML page:

Example

<!DOCTYPE html><html><head>
  <link rel=»stylesheet» href=»styles.css»>
</head><body><h1>This is a heading</h1><p>This is a paragraph.</p></body></html>

The external style sheet can be written in any text editor. The file must not contain any
HTML code, and must be saved with a .css extension.

Here is what the «styles.css» file looks like:

«styles.css»:

body {  background-color: powderblue;}h1 {  color: blue;}p {  color: red;}

Tip: With an external style sheet, you can change the look of an entire web site, by changing one file!

HTML Tutorial

HTML HOMEHTML IntroductionHTML EditorsHTML BasicHTML ElementsHTML AttributesHTML HeadingsHTML ParagraphsHTML StylesHTML FormattingHTML QuotationsHTML CommentsHTML Colors
Colors
RGB
HEX
HSL

HTML CSSHTML Links
Links
Link Colors
Link Bookmarks

HTML Images
Images
Image Map
Background Images
The
Picture Element

HTML TablesHTML Lists
Lists
Unordered Lists
Ordered Lists
Other Lists

HTML Block & InlineHTML ClassesHTML IdHTML IframesHTML JavaScriptHTML File PathsHTML HeadHTML LayoutHTML ResponsiveHTML ComputercodeHTML SemanticsHTML Style GuideHTML EntitiesHTML SymbolsHTML EmojisHTML CharsetHTML URL EncodeHTML vs. XHTML

HTML Reference

HTML by AlphabetHTML by CategoryHTML Browser SupportHTML AttributesHTML Global AttributesHTML EventsHTML ColorsHTML CanvasHTML Audio/VideoHTML Character SetsHTML DoctypesHTML URL EncodeHTML Language CodesHTML Country CodesHTTP MessagesHTTP MethodsPX to EM ConverterKeyboard Shortcuts

HTML Tags

<!—>
<!DOCTYPE>
<a>
<abbr>
<acronym>
<address>
<applet>
<area>
<article>
<aside>
<audio>
<b>
<base>
<basefont>
<bdi>
<bdo>
<big>
<blockquote>
<body>
<br>
<button>
<canvas>
<caption>
<center>
<cite>
<code>
<col>
<colgroup>
<data>
<datalist>
<dd>
<del>
<details>
<dfn>
<dialog>
<dir>
<div>
<dl>
<dt>
<em>
<embed>
<fieldset>
<figcaption>
<figure>
<font>
<footer>
<form>
<frame>
<frameset>
<h1> — <h6>
<head>
<header>
<hr>
<html>
<i>
<iframe>
<img>
<input>
<ins>
<kbd>
<label>
<legend>
<li>
<link>
<main>
<map>
<mark>
<meta>
<meter>
<nav>
<noframes>
<noscript>
<object>
<ol>
<optgroup>
<option>
<output>
<p>
<param>
<picture>
<pre>
<progress>
<q>
<rp>
<rt>
<ruby>
<s>
<samp>
<script>
<section>
<select>
<small>
<source>
<span>
<strike>
<strong>
<style>
<sub>
<summary>
<sup>
<svg>
<table>
<tbody>
<td>
<template>
<textarea>
<tfoot>
<th>
<thead>
<time>
<title>
<tr>
<track>
<tt>
<u>
<ul>
<var>
<video>
<wbr>

Отношения документов в HTML

У HTML-тега есть атрибут – сокращение от relationship. Он определяет, в каком отношении находится открытый документ и страница, на которую указывает ссылка.

W3C определяет множество возможных значений для этого атрибута. Например, вы точно знакомы с , который используется для подключения CSS-файлов.

Нас же интересуют сейчас 4 значения:

  • ,
  • ,
  • ,
  • .

Все вместе они называются . Посмотрим, зачем они нужны и как с ними работать.

DNS Prefetch

Это значение атрибута позволяет заранее позаботиться о разрешении доменных имен документов, то есть получить нужный IP-адрес с DNS-сервера.

Предположим, что на сайте есть справочная страница с множеством ссылок на дочерний сайт. Таким образом, имеется высокая вероятность того, что пользователь на этот дочерний сайт перейдет. Ранний поиск DNS может сократить время, необходимое для открытия сайта (тем самым улучшая пользовательский опыт).

<link rel=»dns-prefetch» href=»//othersite.org»>

1
2
3

<link rel=»dns-prefetch»href=»//othersite.org»>

Когда браузер видит этот код на справочной странице, он добавляет DNS-поиск дочернего сайта в очередь задач. Когда закончатся все высокоприоритетные задачи, он займется этим делом и найдет нужный IP-адрес.

Теперь, если юзер нажмет на ссылку, браузер сразу же приступает к установке TCP-соединения, минуя обращение к DNS-серверу.

Preconnect

Значение заставляет браузер идти еще дальше и устанавливать соединение с сервером, на который в будущем может быть отправлен запрос.

Идеальный вариант использования для – редиректы, которые используются в вебе очень часто. Если следующий запрос браузера однозначно предсказуем (вы собираетесь сделать перенаправление), стоит сразу же загрузить нужный сайт, чтобы уменьшить задержку при его загрузке.

<link rel= «preconnect» href= «//othersite.com»>

1
2
3

<link rel=»preconnect»href=»//othersite.com»>

Prefetch

Если для ресурса указано отношение , браузер обращается к DNS-серверу за его доменным именем, выполняет TCP-соединение, делает HTTP-запрос и, наконец, извлекает и сохраняет ресурс в кэше. И все это в фоне, без явных действий пользователя.

С этим значением следует обращаться очень осторожно. Если вы не угадаете, куда хочет отправиться юзер следующим шагом, то можете не ускорить, а даже замедлить свой сайт

Иногда правильно предсказать действия пользователя очень сложно, поэтому как следует подумайте, следует ли использовать .

Один из кейсов использования этого значения – онлайн-книги/галереи/портфолио с постраничной пагинацией. Вероятность того, что юзер перейдет на следующую страницу высока, так что можно заранее загрузить ресурсы с нее, например, изображения.

<link rel=»prefetch» href=»//site.com/nextimage.jpg»>

1
2
3

<link rel=»prefetch»href=»//site.com/nextimage.jpg»>

Prerender

Значение можно использовать только для HTML-страниц. Они будут полностью отрендерены в offline-режиме, а как только пользователь захочет перейти на них – сразу же показаны.

Это требует большой вычислительной работы и много памяти. Также для рендеринга страницы браузеру могут потребоваться дополнительные ресурсы (например, изображения, добавленные на страницу), что приведет к увеличению количества запросов.

Не злоупотребляйте этой мощной возможностью.

<link rel=»prerender» href=»//site.com/about.html»>

1
2
3

<link rel=»prerender»href=»//site.com/about.html»>

HTML Теги

<!—…—><!DOCTYPE><a><abbr><acronym><address><applet><area><article><aside><audio><b><base><basefont><bdi><bdo><big><blockquote><body><br><button><canvas><caption><center><cite><code><col><colgroup><data><datalist><dd><del><details><dfn><dialog><dir><div><dl><dt><em><embed><fieldset><figcaption><figure><font><footer><form><frame><frameset><h1> — <h6><head><header><hr><html><i><iframe><img><input><ins><kbd><label><legend><li><link><main><map><mark><meta><meter><nav><noframes><noscript><object><ol><optgroup><option><output><p><param><picture><pre><progress><q><rp><rt><ruby><s><samp><script><section><select><small><source><span><strike><strong><style><sub><summary><sup><svg><table><tbody><td><template><textarea><tfoot><th><thead><time><title><tr><track><tt><u><ul><var><video>

Способы асинхронной загрузки CSS

Существует несколько способов заставить браузер загружать CSS асинхронно.

Первый способ (работает в современных браузерах) заключается в использовании JavaScript для создания и вставки ссылки на файл CSS в DOM:

// Создаем ссылку на таблицу стилей
var myCSS = document.createElement( "link" );
myCSS.rel = "stylesheet";
myCSS.href = "mystyles.css";
// вставляем ее в конце блока head
document.head.insertBefore( myCSS, document.head.childNodes.nextSibling );

Второй способ заключается в том, чтобы задать  атрибуту media в теге link значение, которое не соответствует устройству пользователя. Например, media=»print».

В результате браузеры будут воспринимать стили для неиспользуемых устройств как низкоприоритетные. Поэтому они будут загружать стили, не блокируя рендеринг страницы.

Но чтобы задействовать асинхронно загруженные стили, нужно использовать JavaScript-обработчик события onload. Это позволит изменить значение media на соответствующее браузеру и устройству пользователя. Например, screen или all:

<link rel="stylesheet" href="mystyles.css" media="nope!" onload="this.media='all'">

Примечание: мы используем комбинацию перечисленных выше приемов в библиотеке loadCSS.js, предназначенной для обработки асинхронной загрузки CSS. А также обходные пути для устаревших версий браузеров, которые не поддерживают события onload в элементах link.

Также можно загружать CSS асинхронно, используя значение rel=»alternate stylesheet». Оно используется для того, чтобы предложить пользователю альтернативное представление сайта:

<link rel="alternate stylesheet" href="mystyles.css" onload="this.rel='stylesheet'">

Методы, описанные выше, работают. Но у них есть один общий недостаток: они используют JavaScript.

What is CSS?

Cascading Style Sheets (CSS) is used to format the layout of a webpage.

With CSS, you can control the color, font, the size of text, the spacing
between elements, how elements are positioned and laid out, what background
images or background colors are to be used, different displays for different devices
and screen sizes, and much more!

Tip: The word cascading means that a style
applied to a parent element will also apply to all children elements within the
parent. So, if you set the color of the body text to «blue», all headings,
paragraphs, and other text elements within the body will also get the same color (unless you specify
something else)!

Client-Side Image Maps

Client side image maps are enabled by the usemap attribute of the <img /> tag and defined by special <map> and <area> extension tags.

The image that is going to form the map is inserted into the page using the <img /> tag as a normal image, except it carries an extra attribute called usemap. The value of the usemap attribute is the value which will be used in a <map> tag to link map and image tags. The <map> along with <area> tags define all the image coordinates and corresponding links.

The <area> tag inside the map tag, specifies the shape and the coordinates to define the boundaries of each clickable hotspot available on the image. Here’s an example from the image map −

<!DOCTYPE html>
<html>

   <head>
      <title>USEMAP Hyperlink Example</title>
   </head>
	
   <body>
      <p>Search and click the hotspot</p>
      <img src = /images/html.gif alt = "HTML Map" border = "0" usemap = "#html"/>
      <!-- Create  Mappings -->
      
      <map name = "html">
         <area shape = "circle" coords = "80,80,20" 
            href = "/css/index.htm" alt = "CSS Link" target = "_self" />
         
         <area shape = "rect" coords = "5,5,40,40" alt = "jQuery Link" 
            href = "/jquery/index.htm" target = "_self" />
      </map>
   </body>
   
</html>

This will produce the following result −

HTTP-запросы

Прежде чем приступать к оптимизации, освежим в памяти, как происходит типичный HTTP-запрос.

Джо хочет посетить какой-то веб-сайт.

  1. Он вспоминает его человекопонятный адрес, вводит в адресную строку браузера и нажимает .
  2. Браузер обращается к DNS-серверу, чтобы получить соответствующий адресу IP.
  3. Получив IP, браузер отправляет TCP-сообщение на сервер веб-сайта, запрашивая соединение.
  4. Если сервер нормально работает, он подтверждает запрос и отправляет браузеру сообщение, которое он в свою очередь подтверждает (вот такая light-версия TCP-рукопожатия).
  5. Когда все рукопожатия завершены, устанавливается соединение между клиентом (браузером) и сервером.
  6. Браузер переходит с TCP на HTTP и запрашивает веб-страницу, которую Джо терпеливо ждет перед монитором.
  7. Сервер передает браузеру запрошенную страницу.

Чтобы добраться до нужного документа через интернет, требуется пройти множество этапов. Чем раньше этот процесс начнется, тем быстрее мы получим желаемое.

Server-Side Image Maps

Here you simply put your image inside a hyper link and use ismap attribute which makes it special image and when the user clicks some place within the image, the browser passes the coordinates of the mouse pointer along with the URL specified in the <a> tag to the web server. The server uses the mouse-pointer coordinates to determine which document to deliver back to the browser.

When ismap is used, the href attribute of the containing <a> tag must contain the URL of a server application like a cgi or PHP script etc. to process the incoming request based on the passed coordinates.

The coordinates of the mouse position are screen pixels counted from the upper-left corner of the image, beginning with (0,0). The coordinates, preceded by a question mark, are added to the end of the URL.

For example, if a user clicks 20 pixels over and 30 pixels down from the upper-left corner of the following image −

Which has been generated by the following code snippet −

<!DOCTYPE html>
<html>

   <head>
      <title>ISMAP Hyperlink Example</title>
   </head>
	
   <body>
      <p>Click following link</p>
      
      <a href = "/cgi-bin/ismap.cgi" target = "_self"> 
         <img ismap src = "/images/logo.png" alt = "Tutorials Point" border = "0"/> 
      </a>
   </body>
	
</html>

Then the browser sends the following search parameters to the web server which can be processed by ismap.cgi script or map file and you can link whatever documents you like to these coordinates −

/cgi-bin/ismap.cgi?20,30

This way you can assign different links to different coordinates of the image and when those coordinates are clicked, you can open corresponding linked document. To learn more about ismap attribute, you can check How to use Image ismap?

File Download Dialog Box

Sometimes it is desired that you want to give an option where a user will click a link and it will pop up a «File Download» box to the user instead of displaying actual content. This is very easy and can be achieved using an HTTP header in your HTTP response.

For example, if you want make a Filename file downloadable from a given link then its syntax will be as follows.

#!/usr/bin/perl

# Additional HTTP Header
print "Content-Type:application/octet-stream; name = \"FileName\"\r\n";
print "Content-Disposition:attachment; filename = \"FileName\"\r\n\n";

# Open the target file and list down its content as follows
open( FILE, "<FileName" );

while(read(FILE, $buffer, 100)){
   print("$buffer");
}

Note − For more detail on PERL CGI programs, go through tutorial PERL and CGI.

Previous Page
Print Page

Next Page  

HTML Tags

<!—><!DOCTYPE><a><abbr><acronym><address><applet><area><article><aside><audio><b><base><basefont><bdi><bdo><big><blockquote><body><br><button><canvas><caption><center><cite><code><col><colgroup><data><datalist><dd><del><details><dfn><dialog><dir><div><dl><dt><em><embed><fieldset><figcaption><figure><font><footer><form><frame><frameset><h1> — <h6><head><header><hr><html><i><iframe><img><input><ins><kbd><label><legend><li><link><main><map><mark><meta><meter><nav><noframes><noscript><object><ol><optgroup><option><output><p><param><picture><pre><progress><q><rp><rt><ruby><s><samp><script><section><select><small><source><span><strike><strong><style><sub><summary><sup><svg><table><tbody><td><template><textarea><tfoot><th><thead><time><title><tr><track><tt><u><ul><var><video>

HTML Links — The target Attribute

By default, the linked page will be displayed in the current browser window.
To change this, you must specify another target for the link.

The attribute specifies where to open the linked document.

The attribute can have one of the following values:

  • — Default. Opens the document in
    the same window/tab as it was clicked
  • — Opens the document in a new window or tab
  • — Opens the document in the parent frame
  • — Opens the document in the full body of the window

Example

Use target=»_blank» to open the linked document in a new browser window or tab:

<a href=»https://www.w3schools.com/»
target=»_blank»>Visit W3Schools!</a>

Setting Link Colors

You can set colors of your links, active links and visited links using link, alink and vlink attributes of <body> tag.

Example

Save the following in test.htm and open it in any web browser to see how link, alink and vlink attributes work.

<!DOCTYPE html>
<html>
   
   <head>
      <title>Hyperlink Example</title>
      <base href = "https://www.tutorialspoint.com/">
   </head>
	
   <body alink = "#54A250" link = "#040404" vlink = "#F40633">
      <p>Click following link</p>
      <a href = "/html/index.htm" target = "_blank" >HTML Tutorial</a>
   </body>
   
</html>

This will produce the following result. Just check color of the link before clicking on it, next check its color when you activate it and when the link has been visited.

Creating Links in HTML

A link or hyperlink is a connection from one web resource to another. Links allow users to move seamlessly from one page to another, on any server anywhere in the world.

A link has two ends, called anchors. The link starts at the source anchor and points to the destination anchor, which may be any web resource, for example, an image, an audio or video clip, a PDF file, an HTML document or an element within the document itself, and so on.

By default, links will appear as follow in most of the browsers:

  • An unvisited link is underlined and blue.
  • A visited link is underlined and purple.
  • An active link is underlined and red.

However, you can overwrite this using CSS. Learn more about styling links.

Современный метод

Существует решение, созданное специально для асинхронной загрузки CSS файлов: rel=»preload». Но даже этот вариант использует обработчик события onload.

Ниже приведен использования rel=»preload»:

<link rel="preload" href="mystyles.css" as="style" onload="this.rel='stylesheet'">

Значение атрибута rel=»preload» заставляет браузеры (которые его поддерживают) загружать, но не применять указанный файл. Поэтому необходим обработчик события onload, чтобы установить атрибут rel в значение stylesheet после загрузки.

Вариант с rel=»preload» имеет одно важное преимущество: браузеры начнут загружать CSS раньше, чем при использовании подхода с несоответствующим значением атрибута media

CSS Advanced

CSS Rounded CornersCSS Border ImagesCSS BackgroundsCSS ColorsCSS Color KeywordsCSS Gradients
Linear Gradients
Radial Gradients

CSS Shadows
Shadow Effects
Box Shadow

CSS Text EffectsCSS Web FontsCSS 2D TransformsCSS 3D TransformsCSS TransitionsCSS AnimationsCSS TooltipsCSS Style ImagesCSS Image ReflectionCSS object-fitCSS object-positionCSS ButtonsCSS PaginationCSS Multiple ColumnsCSS User InterfaceCSS Variables
The var() Function
Overriding Variables
Variables and JavaScript
Variables in Media Queries

CSS Box SizingCSS Media QueriesCSS MQ ExamplesCSS Flexbox
CSS Flexbox
CSS Flex Container
CSS Flex Items
CSS Flex Responsive

Параметр MEDIA

HTML: 3.2 4 XHTML: 1.0 1.1

Описание

Определяет устройство, для которого следует применять стилевое оформление. Это позволяет сделать разный стиль для отображения документа на экране монитора и при его печати. Допускается писать несколько аргументов через запятую.

Аргументы

all
Все устройства .
screen
Экран монитора.
print
Печатающее устройство вроде принтера.
projection
Проектор.
braille
Устройства, основанные на системе Брайля, которые предназначены для слепых людей.
speech
Речевые синтезаторы, а также программы для воспроизведения текста вслух. Сюда, например, можно отнести речевые браузеры.

Attribute Values

Value Description
alternate Provides a link to an alternate version of the document (i.e. print page, translated or mirror).
Example: <link rel=»alternate» type=»application/atom+xml» title=»W3Schools News» href=»/blog/news/atom»>
author Provides a link to the author of the document
dns-prefetch Specifies that the browser should preemptively perform DNS resolution for the target resource’s origin
help Provides a link to a help document. Example: <link rel=»help» href=»/help/»>
icon Imports an icon to represent the document.Example: <link rel=»icon» href=»/favicon.ico» type=»image/x-icon»>
license Provides a link to copyright information for the document
next Provides a link to the next document in the series
pingback Provides the address of the pingback server that handles pingbacks to the current document
preconnect Specifies that the browser should preemptively connect to the target resource’s origin.
prefetch Specifies that the browser should preemptively fetch and cache the target resource as it is likely to be required for a follow-up navigation
preload Specifies that the browser agent must preemptively fetch and cache the target resource for current navigation according to the destination given by the «as» attribute (and the priority associated with that destination).
prerender Specifies that the browser should pre-render (load) the specified
webpage in the background. So, if the user navigates to this page, it speeds
up the page load (because the page is already loaded). Warning!
This waste the user’s bandwidth! Only use prerender if it is absolutely sure
that the webpage is required at some point in the user journey
prev Indicates that the document is a part of a series, and that the previous document in the series is the referenced document
search Provides a link to a resource that can be used to search through the current document and its related pages.
stylesheet Imports a style sheet

❮ HTML <link> tag

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector