How to link html to html

How to link html to html

Что такое HTML импорт и как это работает?

Перевод статьи «What are HTML Imports and How Do They Work?», Paula Borowska.

Вы когда-нибудь замечали, что включение одной HTML страницы в другую, это какая-то инородная концепция? Это то, что должно быть просто, но не это не часто происходит. Это не невозможно, но трудно. К счастью есть HTML импорт, который позволяет запросто помещать HTML страницы, а также CSS и JavaScript файлы, внутрь других HTML страниц.

Введение в HTML импорт

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

Интересно то, что HTML это самые простые файлы, но иногда с ними труднее всего работать. Даже PHP файлы имеют возможность включения, почему же HTML этого не может? Благодаря веб-компонентам, мы, теперь, можем включать одни HTML документы в другие. Также, при помощи этого же тега, мы можем подключать CSS и JavaScript. (Жить стало намного лучше.)

Обходные пути

Раньше, одним из обходных путей было подключение при помощи iFrame; это тяжелые HTML элементы, загружаемые отдельным окном внутри текущего документа. Это немного не то, что нам нужно и при этом с ними, не очень то легко взаимодействовать. iFram’ы могут быть удивительно разочаровывающими, когда с ними приходится работать. Следующим вариантом был AJAX, это когда вы загружали страницу при помощи JavaScript и включали её контент. Это, на самом деле, довольно неудобный и утомительный способ.

Начнём

Базовый синтаксис

Прежде чем смотреть примеры, давайте глянем на синтаксис подгрузки файла через тег импорта. Импорт, это новый тип link тега, так что должно быть нетрудно понять следующую строчку:

Такие строки помещаются в шапке, как вы уже привыкли поступать с JavaScript или CSS файлами.

Базовый пример

Чтобы импорт сработал, страницы должны находиться на одном и том же сервере. Начнем с файла index.html. Это простая HTML страница с базовым импортом:

How to link html to html. Смотреть фото How to link html to html. Смотреть картинку How to link html to html. Картинка про How to link html to html. Фото How to link html to html

Видите, я не врала о том, как все просто; это так же просто, как загрузка таблицы стилей или JavaScript-файла.

Внутри intro.html

Что же внутри импортированной страницы?

Это просто div с текстом внутри. Не нужно body или head или чего-то ещё.

Вставка импортированного HTML

Чтобы отобразить импортированный HTML, нам нужно написать несколько строчек на JavaScript. Этот код должен находиться в главном HTML-файле, в нашем случае, index.html. Данный код должен находиться в том месте, где мы хотим увидеть импортированный html. В нашем примере после ‘Hello from Designmodo.’

В нашем скрипте мы получаем контент и присваиваем его переменной. Потом мы просто добавляем содержимое переменной в HTML.

How to link html to html. Смотреть фото How to link html to html. Смотреть картинку How to link html to html. Картинка про How to link html to html. Фото How to link html to html

Переходим на следующий уровень

Вы когда-нибудь слышали о CSS атрибуте scoped? Атрибут scoped позволяет вам ограничивать действие тега
How to link html to html. Смотреть фото How to link html to html. Смотреть картинку How to link html to html. Картинка про How to link html to html. Фото How to link html to html

Если хотите почитать побольше об атрибуте scoped, посмотрите, что говорит W3C.

12 Links

Contents

12.1 Introduction to links and anchors

HTML offers many of the conventional publishing idioms for rich text and structured documents, but what separates it from most other markup languages is its features for hypertext and interactive documents. This section introduces the link (or hyperlink, or Web link), the basic hypertext construct. A link is a connection from one Web resource to another. Although a simple concept, the link has been one of the primary forces driving the success of the Web.

12.1.1 Visiting a linked resource

The default behavior associated with a link is the retrieval of another Web resource. This behavior is commonly and implicitly obtained by selecting the link (e.g., by clicking, through keyboard input, etc.).

The following HTML excerpt contains two links, one whose destination anchor is an HTML document named «chapter2.html» and the other whose destination anchor is a GIF image in the file «forest.gif»:

By activating these links (by clicking with the mouse, through keyboard input, voice commands, etc.), users may visit these resources. Note that the href attribute in each source anchor specifies the address of the destination anchor with a URI.

Destination anchors in HTML documents may be specified either by the A element (naming it with the name attribute), or by any other element (naming with the id attribute).

We may achieve the same effect by making the header elements themselves the anchors:

12.1.2 Other link relationships

By far the most common use of a link is to retrieve another Web resource, as illustrated in the previous examples. However, authors may insert links in their documents that express other relationships between resources than simply «activate this link to visit that related resource». Links that express other types of relationships have one or more link types specified in their source anchor.

The roles of a link defined by A or LINK are specified via the rel and rev attributes.

For instance, links defined by the LINK element may describe the position of a document within a series of documents. In the following excerpt, links within the document entitled «Chapter 5» point to the previous and next chapters:

The link type of the first link is «prev» and that of the second is «next» (two of several recognized link types). Links specified by LINK are not rendered with the document’s contents, although user agents may render them in other ways (e.g., as navigation tools).

Even if they are not used for navigation, these links may be interpreted in interesting ways. For example, a user agent that prints a series of HTML documents as a single document may use this link information as the basis of forming a coherent linear document. Further information is given below on using links for the benefit of search engines.

12.1.3 Specifying anchors and links

Although several HTML elements and attributes create links to other resources (e.g., the IMG element, the FORM element, etc.), this chapter discusses links and anchors created by the LINK and A elements. The LINK element may only appear in the head of a document. The A element may only appear in the body.

When the A element’s href attribute is set, the element defines a source anchor for a link that may be activated by the user to retrieve a Web resource. The source anchor is the location of the A instance and the destination anchor is the Web resource.

The retrieved resource may be handled by the user agent in several ways: by opening a new HTML document in the same user agent window, opening a new HTML document in a different window, starting a new program to handle the resource, etc. Since the A element has content (text, images, etc.), user agents may render this content in such a way as to indicate the presence of a link (e.g., by underlining the content).

When the name or id attributes of the A element are set, the element defines an anchor that may be the destination of other links.

Authors may set the name and href attributes simultaneously in the same A instance.

The LINK element defines a relationship between the current document and another resource. Although LINK has no content, the relationships it defines may be rendered by some user agents.

12.1.4 Link titles

The title attribute may be set for both A and LINK to add information about the nature of a link. This information may be spoken by a user agent, rendered as a tool tip, cause a change in cursor image, etc.

Thus, we may augment a previous example by supplying a title for each link:

12.1.5 Internationalization and links

Since links may point to documents encoded with different character encodings, the A and LINK elements support the charset attribute. This attribute allows authors to advise user agents about the encoding of data at the other end of the link.

The hreflang attribute provides user agents with information about the language of a resource at the end of a link, just as the lang attribute provides information about the language of an element’s content or attribute values.

Armed with this additional knowledge, user agents should be able to avoid presenting «garbage» to the user. Instead, they may either locate resources necessary for the correct presentation of the document or, if they cannot locate the resources, they should at least warn the user that the document will be unreadable and explain the cause.

12.2 The A element

Start tag: required, End tag: required

name = cdata [CS] This attribute names the current anchor so that it may be the destination of another link. The value of this attribute must be a unique anchor name. The scope of this name is the current document. Note that this attribute shares the same name space as the id attribute. href = uri [CT] This attribute specifies the location of a Web resource, thus defining a link between the current element (the source anchor) and the destination anchor defined by this attribute. hreflang = langcode [CI] This attribute specifies the base language of the resource designated by href and may only be used when href is specified. type = content-type [CI] This attribute gives an advisory hint as to the content type of the content available at the link target address. It allows user agents to opt to use a fallback mechanism rather than fetch the content if they are advised that they will get content in a content type they do not support. Authors who use this attribute take responsibility to manage the risk that it may become inconsistent with the content available at the link target address. For the current list of registered content types, please consult [MIMETYPES]. rel = link-types [CI] This attribute describes the relationship from the current document to the anchor specified by the href attribute. The value of this attribute is a space-separated list of link types. rev = link-types [CI] This attribute is used to describe a reverse link from the anchor specified by the href attribute to the current document. The value of this attribute is a space-separated list of link types. charset = charset [CI] This attribute specifies the character encoding of the resource designated by the link. Please consult the section on character encodings for more details.

Attributes defined elsewhere

Each A element defines an anchor

In the example that follows, the A element defines a link. The source anchor is the text «W3C Web site» and the destination anchor is «http://www.w3.org/»:

This link designates the home page of the World Wide Web Consortium. When a user activates this link in a user agent, the user agent will retrieve the resource, in this case, an HTML document.

User agents generally render links in such a way as to make them obvious to users (underlining, reverse video, etc.). The exact rendering depends on the user agent. Rendering may vary according to whether the user has already visited the link or not. A possible visual rendering of the previous link might be:

To tell user agents explicitly what the character encoding of the destination page is, set the charset attribute:

Suppose we define an anchor named «anchor-one» in the file «one.html».

This creates an anchor around the text «This is the location of anchor one.». Usually, the contents of A are not rendered in any special way when A defines an anchor only.

Having defined the anchor, we may link to it from the same or another document. URIs that designate anchors contain a «#» character followed by the anchor name (the fragment identifier). Here are some examples of such URIs:

Thus, a link defined in the file «two.html» in the same directory as «one.html» would refer to the anchor as follows:

The A element in the following example specifies a link (with href ) and creates a named anchor (with name ) simultaneously:

This example contains a link to a different type of Web resource (a PNG image). Activating the link should cause the image resource to be retrieved from the Web (and possibly displayed if the system has been configured to do so).

Note. User agents should be able to find anchors created by empty A elements, but some fail to do so. For example, some user agents may not find the «empty-anchor» in the following HTML fragment:

12.2.1 Syntax of anchor names

An anchor name is the value of either the name or id attribute when used in the context of anchors. Anchor names must observe the following rules:

Thus, the following example is correct with respect to string matching and must be considered a match by user agents:

ILLEGAL EXAMPLE:
The following example is illegal with respect to uniqueness since the two names are the same except for case:

Although the following excerpt is legal HTML, the behavior of the user agent is not defined; some user agents may (incorrectly) consider this a match and others may not.

12.2.2 Nested links are illegal

Links and anchors defined by the A element must not be nested; an A element must not contain any other A elements.

Since the DTD defines the LINK element to be empty, LINK elements may not be nested either.

12.2.3 Anchors with the id attribute

The id attribute may be used to create an anchor at the start tag of any element (including the A element).

This example illustrates the use of the id attribute to position an anchor in an H2 element. The anchor is linked to via the A element.

The following example names a destination anchor with the id attribute:

ILLEGAL EXAMPLE:
The following excerpt is illegal HTML since these attributes declare the same name twice in the same document.

The following example illustrates that id and name must be the same when both appear in an element’s start tag:

12.2.4 Unavailable and unidentifiable resources

A reference to an unavailable or unidentifiable resource is an error. Although user agents may vary in how they handle such an error, we recommend the following behavior:

12.3 Document relationships: the LINK element

Start tag: required, End tag: forbidden

Attributes defined elsewhere

This example illustrates how several LINK definitions may appear in the HEAD section of a document. The current document is «Chapter2.html». The rel attribute specifies the relationship of the linked document with the current document. The values «Index», «Next», and «Prev» are explained in the section on link types.

12.3.1 Forward and reverse links

Consider two documents A and B.

Has exactly the same meaning as:

Both attributes may be specified simultaneously.

12.3.2 Links and external style sheets

When the LINK element links an external style sheet to a document, the type attribute specifies the style sheet language and the media attribute specifies the intended rendering medium or media. User agents may save time by retrieving from the network only those style sheets that apply to the current device.

Media types are further discussed in the section on style sheets.

12.3.3 Links and search engines

Authors may use the LINK element to provide a variety of information to search engines, including:

The examples below illustrate how language information, media types, and link types may be combined to improve document handling by search engines.

In the following example, we use the hreflang attribute to tell search engines where to find Dutch, Portuguese, and Arabic versions of a document. Note the use of the charset attribute for the Arabic manual. Note also the use of the lang attribute to indicate that the value of the title attribute for the LINK element designating the French manual is in French.

In the following example, we tell search engines where to find the printed version of a manual.

In the following example, we tell search engines where to find the front page of a collection of documents.

Further information is given in the notes in the appendix on helping search engines index your Web site.

12.4 Path information: the BASE element

Start tag: required, End tag: forbidden

href = uri [CT] This attribute specifies an absolute URI that acts as the base URI for resolving relative URIs.

Attributes defined elsewhere

In HTML, links and references to external images, applets, form-processing programs, style sheets, etc. are always specified by a URI. Relative URIs are resolved according to a base URI, which may come from a variety of sources. The BASE element allows authors to specify a document’s base URI explicitly.

When present, the BASE element must appear in the HEAD section of an HTML document, before any element that refers to an external source. The path information specified by the BASE element only affects URIs in the document where the element appears.

For example, given the following BASE declaration and A declaration:

the relative URI «../cages/birds.gif» would resolve to:

12.4.1 Resolving relative URIs

User agents must calculate the base URI for resolving relative URIs according to [RFC1808], section 3. The following describes how [RFC1808] applies specifically to HTML.

User agents must calculate the base URI according to the following precedences (highest priority to lowest):

Additionally, the OBJECT and APPLET elements define attributes that take precedence over the value set by the BASE element. Please consult the definitions of these elements for more information about URI issues specific to them.

Note. For versions of HTTP that define a Link header, user agents should handle these headers exactly as LINK elements in the document. HTTP 1.1 as defined by [RFC2616] does not include a Link header field (refer to section 19.6.3).

How to link html pages in same or different folders?

How can I link to html pages if they are in same or different folders without writing full path?

14 Answers 14

Trending sort

Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.

It falls back to sorting by highest score if no posts are trending.

Switch to Trending sort

Within the same folder, just use the file name:

Within the parent folder’s directory:

Within a sub-directory:

How to link html to html. Смотреть фото How to link html to html. Смотреть картинку How to link html to html. Картинка про How to link html to html. Фото How to link html to html

Also, this will go up a directory and then back down to another subfolder.

To go up multiple directories you can do this.

To go the root, I use this

In addition, if you want to refer to the root directory, you can use:

Which will refer to the root. So, let’s say we’re in a file that’s nested within a few levels of folders and you want to go back to the main index.html:

Robert is spot-on with further relative path explanations.

You can go up a folder in the hierarchy by using

So to get to folder /webroot/site/pages/folder2/mypage.htm from /webroot/site/pages/folder1/myotherpage.htm your link would look like this:

use the relative path

main page might be: /index.html

secondary page: /otherFolder/otherpage.html

link would be like so:

If you’d like to link to the root directory you can use

If you’d like to link to a file in the same directory, simply put the file name

To move back a folder, you can use

To link to the index page in the employees directory from the root directory, you’d do this

I would caution you: if you are using absolute paths, then your application cannot be installed in a «subdirectory» of the server!

. is for current directory

Simple yet tricky, I write this answer primarily for myself not to forget next time.

The link to CSS in index.html :

This case it should be:

In this case path must be:

For example if your file, lets say image is in folder1 in folder2 you locate it this way

How to link html to html. Смотреть фото How to link html to html. Смотреть картинку How to link html to html. Картинка про How to link html to html. Фото How to link html to html

Answer below is what I created to link html contents from another shared drive to the html page I would send out to managers. Of course, the path is relative to your using, but in my case, I would just send them the html, and everything else that is updated from load runner dynamically would be updated for me. Saves tons of paper, and they can play with the numbers as they see fit instead of just a hard copy this way.

HTML Links: How to create Links to other Web Pages

This article explains how to create a link from one page to another. It also outlines the different types of hyperlinks.

Hypertext references can use URLS, URLs, or URLs.

This refers to a URL where the full path is provided. For example:

This refers to a URL where the path, relative to the current location, is provided.

This refers to a URL where the path, relative to the domain’s root, is provided.

The forward slash indicates the domain’s root. No matter where your file is located, you can always use this method to specify the path, even if you don’t know what the domain name will eventually be (as long as you know the full path from the root).

Link Targets

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

The target attribute can have the following possible values:

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

Jump Links

You can make your links «jump» to other sections within the same page (or another page). These used to be called «named anchors», but they’re often referred to as jump links, bookmarks, or fragment identifiers.

Here’s how to link to the same page:

Add an ID to the Link Target

Add an ID to the part of the page that you want the user to end up. To do this, use the id attribute. The value should be some short descriptive text. The id attribute is a commonly used attribute in HTML.

Create the Hyperlink

Now create the hyperlink (that the user will click on). This is done by using the id of the link target, preceded by a hash ( # ) symbol:

So these two pieces of code are placed in different parts of the document. Something like this:

It doesn’t have to be the same page. You can use this method to jump to an ID of any page. To do this, simply add the destination URL before the hash ( # ) symbol. Example:

Of course, this assumes that there’s an ID with that value on the page.

Email Links

You can create a hyperlink to an email address. To do this, use the mailto attribute in your anchor tag.

Clicking on this link should result in your default email client opening up with the email address already filled out.

You can go a step further than this. You can auto-complete the subject line for your users, and even the body of the email. You do this appending subject and body parameters to the email address.

Base href

HTML Links

In this tutorial you will learn how to create links to other pages in HTML.

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:

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

HTML Link Syntax

Links are specified in HTML using the tag.

A link or hyperlink could be a word, group of words, or image.

Anything between the opening tag and the closing tag becomes the part of the link that the user sees and clicks in a browser. Here are some examples of the links:

Example

The href attribute specifies the target of the link. Its value can be an absolute or relative URL.

Setting the Targets for Links

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

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

Example

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

Creating Bookmark Anchors

You can also create bookmark anchors to allow users to jump to a specific section of a web page. Bookmarks are especially helpful if you have a very long web page.

Creating bookmarks is a two-step process: first add the id attribute on the element where you want to jump, then use that id attribute value preceded by the hash sign ( # ) as the value of the href attribute of the tag, as shown in the following example:

Example

Creating Download Links

You can also create the file download link in exactly the same fashion as placing text links. Just point the destination URL to the file you want to be available for download.

In the following example we’ve created the download links for ZIP, PDF and JPG files.

Example

Note: When you click a link that points to a PDF or image file, the file is not downloaded to your hard drive directly. It will only open the file in your web browser. Further you can save or download it to your hard drive on a permanent basis.

Источники информации:

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

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