하이퍼링크 만들기

하이퍼 링크는 중요하다. — 웹을 웹답게 만들기 때문이다. 이 글에서는 링크를 만드는데 필요한 구문을 보여주고 링크의 모범 사례를 설명한다.

미리 알아두면 좋은 지식들: 기본적인 HTML 에 대한 친숙함, as covered in Getting started with HTML. HTML text formatting, as covered in HTML text fundamentals.
목표:

하이퍼링크를 효과적으로 다루는 방법과 수많은 파일들을 함께 연결하는 방법을 배웁니다.

하이퍼링크란 무엇인가?

하이퍼링크는 웹이 제공하는 가장 흥미로운 혁신 중 하나입니다, 하이퍼링크는 웹이 시작된 이래 웹의 특성이었습니다. 그러나 하이퍼링크는 웹을 웹 다워보이도록 만들어줍니다. — 문서들을 다른 문서들과 연결시켜 주기도 하구요. 또는 우리가 원하는 다른 resource 들과 연결해주기도 합니다. 우리는 또한 문서들의 특정 부분들끼리 연결할 수 있죠.그리고 우리는 앱들을 단순한 웹 주소를 통해 이용하게 만들 수도 있습니다. (설치 혹은 여러가지 작업들을 필요로 하는 native 앱과 비교해보세요.) 거의 모든 web content 들은 링크로 바뀔 수 있는데요. 우리가 그것들을 클릭하거나 활성화시키면 웹 브라우저가 다른 웹 주소(URL)로 갑니다. 

메모:  URL은 HTML 파일, 텍스트 파일, 이미지, 텍스트 문서들, 비디오와 오디오 파일들, 그리고 웹상에서 존재할 수 있는 어느 것이라 할지라도 연결할 수 있다.만약 웹 브라우저가 어떻게 파일을 보여주거나 다룰지 모른다면, 웹 브라우저는 당신이 파일을 열기를 원하는지 (만약 그렇다면, 파일을 열거나 처리하는 것에 대한 의무는 device에서 적절한 native 앱에게 넘겨질 겁니다.) 혹은 파일을 다운로드 하기를 원하는지 (만약 그렇다면, 당신은 그것을 나중에 다룰 수 있습니다.) 궁금해 할 것입니다.

예를 들면, BBC 홈페이지엔 많은 링크들이 있는데요. 그것들은 다양한 뉴스들에 연결

예를 들면, BBC 홈페이지엔 많은 링크들이 있는데요. 그것들은 수많은 뉴스들 뿐만 아니라 다른 웹사이트들 (navigation functionality), 로그인/등록 페이지들 (user tools) 그리고 더 많은 다른 곳에도 연결되어 있습니다.

frontpage of bbc.co.uk, showing many news items, and navigation menu functionality

링크의 구조

A basic link is created by wrapping the text (or other content, see Block level links) you want to turn into a link inside an <a> element, and giving it an href attribute (also known as a target) that will contain the web address you want the link to point to.

<p>I'm creating a link to
<a href="https://www.mozilla.org/en-US/">the Mozilla homepage</a>.
</p>

위 코드의 결과는 다음과 같습니다:

I'm creating a link to the Mozilla homepage.

title 속성에 부가적인 정보를 더하기

Another attribute you may want to add to your links is title; this is intended to contain supplementary useful information about the link, such as what kind of information the page contains, or things to be aware of. For example:

<p>I'm creating a link to
<a href="https://www.mozilla.org/en-US/"
   title="The best place to find more information about Mozilla's
          mission and how to contribute">the Mozilla homepage</a>.
</p>

This gives us the following result (the title will come up as a tooltip when the link is hovered over):

I'm creating a link to the Mozilla homepage.

Note: A link title is only revealed on mouse hover, which means that people relying on keyboard controls to navigate web pages will have difficulty accessing title information. 만약 title의 정보가 페이지 사용에 있어서 정말로 중요하다면,  then you should present it in a manner that will be accessible to all users, for example by putting it in the regular text.

능동학습: 링크를 만들어봅시다.

적극적으로 학습해 봅시다: local code 편집기를 사용해서 하나의 HTML document 를 만드세요. (소스코드: 템플릿 시작하기가 잘 될거에요.)

  • HTML body 속에, 하나의 혹은 더 많은 paragraph 들, 혹은 당신이 이미 알고 있는 다른 타입의 content 들을 더해보세요.
  • 몇몇의 content들을 링크로 바꾸세요.
  • 타이틀 속성들을 더하세요.

Block level 링크들

이전에 얘기했듯이, 여러분은 어떤 내용이든 link로 바꿀 수 있습니다. block level 요소들 이라고 할지라도요. 만약 링크로 바꾸고 싶은 이미지가 있다면, <a> 와 </a> 사이에 그 이미지를 넣으시기만 하시면 됩니다.

<a href="https://www.mozilla.org/en-US/">
  <img src="mozilla-image.png" alt="mozilla logo that links to the mozilla homepage">
</a>

메모: 나중에 보실 글에선 웹에서 이미지를 사용하는 것에 대해 더 많이 배우실 겁니다.

URL 과 path 에 대한 기본 지침

 link target 에 대해 완전히 이해하기 위해서, URL 과 파일 path에 대하여 이해하실 필요가 있습니다. 이번 시간에는 여러분께서 성취하실 필요가 있는 정보에 대해서 알려드릴게요.

URL, 혹은 Uniform Resource Locator 은 단순히 무언가가 웹상의 어디에 위치하는지 결정하는 하나의 텍스트 문자열이랍니다. 예를 들면, Mozilla's 영어 홈페이지는https://www.mozilla.org/en-US/이죠.

URL은 파일들을 찾기위해 path를 이용합니다. path는 당신이 관심있어 하는 파일이 파일 시스템 어디에 있는지 구체적으로 명시하구요. 디렉토리 구조에 대한 예제를 보시죠. (see the creating-hyperlinks directory.)

A simple directory structure. The parent directory is called creating-hyperlinks and contains two files called index.html and contacts.html, and two directories called projects and pdfs, which contain an index.html and a project-brief.pdf file, respectively

The root of this directory structure is called creating-hyperlinks. When working locally with a web site, you will have one directory that the whole site goes inside. Inside the root, we have an index.html file and a contacts.html. In a real website, index.html would be our home page or landing page.

There are also two directories inside our root — pdfs and projects. These each have a single file inside them — a PDF (project-brief.pdf) and an index.html file, respectively. Note how you can quite happily have two index.html files in one project as long as they are in different locations in the filesystem. Many web sites do. The second index.html would perhaps be the main landing page for project-related information.

  • Same directory: If you wanted to include a hyperlink inside index.html (the top level index.html) pointing to contacts.html, you would just need to specify the filename of the file you want to link to, as it is in the same directory as the current file. So the URL you would use is contacts.html:

    <p>Want to contact a specific staff member?
    Find details on our <a href="contacts.html">contacts page</a>.</p>
  • Moving down into subdirectories: If you wanted to include a hyperlink inside index.html (the top level index.html) pointing to projects/index.html, you would need to go down into the projects directory before indicating the file you want to link to. This is done by specifying the directory's name, then a forward slash, then the name of the file. so the URL you would use is projects/index.html:

    <p>Visit my <a href="projects/index.html">project homepage</a>.</p>
  • Moving back up into parent directories: If you wanted to include a hyperlink inside projects/index.html pointing to pdfs/project-brief.pdf, you'd have to go up a directory level, then back down into the pdf directory. "Go up a directory" is indicated using two dots — .. — so the URL you would use is ../pdfs/project-brief.pdf:

    <p>A link to my <a href="../pdfs/project-brief.pdf">project brief</a>.</p>

Note: You can combine multiple instances of these features into complex URLs, if needed, e.g. ../../../complex/path/to/my/file.html.

Document fragments

It is possible to link to a specific part of an HTML document (known as a document fragment), rather than just to the top of the document. To do this you first have to assign an id attribute to the element you want to link to. It normally makes sense to link to a specific heading, so this would look something like the following:

<h2 id="Mailing_address">Mailing address</h2>

Then to link to that specific id, you'd include it at the end of the URL, preceded by a hash/pound symbol, for example:

<p>Want to write us a letter? Use our <a href="contacts.html#Mailing_address">mailing address</a>.</p>

You can even use the document fragment reference on its own to link to another part of the same document:

<p>The <a href="#Mailing_address">company mailing address</a> can be found at the bottom of this page.</p>

Absolute versus relative URLs

Two terms you'll come across on the Web are absolute URL and relative URL:

absolute URL: Points to a location defined by its absolute location on the web, including protocol and domain name. So for example, if an index.html page is uploaded to a directory called projects that sits inside the root of a web server, and the web site's domain is http://www.example.com, the page would be available at http://www.example.com/projects/index.html (or even just http://www.example.com/projects/, as most web servers just look for a landing page such as index.html to load if it is not specified in the URL.)

An absolute URL will always point to the same location, no matter where it is used.

relative URL: Points to a location that is relative to the file you are linking from, more like what we looked at in the previous section. For example, if we wanted to link from our example file at http://www.example.com/projects/index.html to a PDF file in the same directory, the URL would just be the filename — e.g. project-brief.pdf — no extra information needed. If the PDF was available in a subdirectory inside projects called pdfs, the relative link would be pdfs/project-brief.pdf (the equivalent absolute URL would be http://www.example.com/projects/pdfs/project-brief.pdf.)

A relative URL will point to different places depending on where the file it is used inside is located — for example if we moved our index.html file out of the projects directory and into the root of the web site (the top level, not in any directories), the pdfs/project-brief.pdf relative URL would now point to http://www.example.com/pdfs/project-brief.pdf, not http://www.example.com/projects/pdfs/project-brief.pdf.

There are some best practices to follow when writing links. Let's look at these now.

It's easy to throw links up on your page. That's not enough. We need to make our links accessible to all readers, regardless of their current context and which tools they prefer. For example:

  • Screenreader users like jumping around from link to link on the page, and reading links out of context.
  • Search engines use link text to index target files, so it is a good idea to include keywords in your link text to effectively describe what is being linked to.
  • Visual readers skim over the page rather than reading every word, and their eyes will be drawn to page features that stand out, like links. They will find descriptive link text useful.

Let's look at a specific example:

Good link text: Download Firefox

<p><a href="https://firefox.com/">
  Download Firefox
</a></p>

Bad link text: Click here to download Firefox

<p><a href="https://firefox.com/">
  Click here
</a>
to download Firefox</p>

Other tips:

  • Don't repeat the URL as part of the link text — URLs look ugly, and sound even uglier when a screen reader reads them out letter by letter.
  • Don't say "link" or "links to" in the link text — it's just noise. Screen readers tell people there's a link. Visual users will also know there's a link, because links are generally styled in a different colour and underlined (this convention generally shouldn't be broken, as users are so used to it.)
  • Keep your link label as short as possible — long links especially annoy screen reader users, who have to hear the whole thing read out.
  • Minimize instances where multiple copies of the same text are linked to different places. This can cause problems for screenreader users, who will often bring up a list of the links out of context — several links all labelled "click here", "click here", "click here" would be confusing.

From the description above, you might think that it is a good idea to just use absolute links all the time; after all, they don't break when a page is moved like relative links. However, you should use relative links wherever possible when linking to other locations within the same website (when linking to another website, you will need to use an absolute link):

  • For a start, it is a lot easier to scan your code — relative URLs are generally a lot shorter than absolute URLs, which makes reading code much easier.
  • Second, it is more efficient to use relative URLs wherever possible. When you use an absolute URL, the browser starts by looking up the real location of the server by querying the domain name with the DNS, then it goes to that server and finds the file that is being requested. With a relative URL on the other hand, the browser just looks up the file that is being requested, on the same server. So if you use absolute URLs where relative URLs would do, you are constantly making your browser do extra work, meaning that it will perform less efficiently.

Linking to non-HTML resources — leave clear signposts

When linking to a resource that will be downloaded (like a PDF or Word document) or streamed (like video or audio) or has another potentially unexpected effect (opens a popup window, or loads a Flash movie), you should add clear wording to reduce any confusion. It can be quite annoying for example:

  • If you are on a low bandwidth connection, click a link and then a multiple megabyte download starts unexpectedly.
  • If you haven't got the Flash player installed, click a link and then suddenly get taken to a page that requires Flash.

Let's look at some examples, to see what kind of text can be used here:

<p><a href="http://www.example.com/large-report.pdf">
  Download the sales report (PDF, 10MB)
</a></p>

<p><a href="http://www.example.com/video-stream/">
  Watch the video (stream opens in separate tab, HD quality)
</a></p>

<p><a href="http://www.example.com/car-game">
  Play the car game (requires Flash)
</a></p>

Use the download attribute when linking to a download

When you are linking to a resource that is to be downloaded rather than opened in the browser, you can use the download attribute to provide a default save filename. Here's an example with a download link to the Windows version of Firefox 39:

<a href="https://download.mozilla.org/?product=firefox-39.0-SSL&os=win&lang=en-US"
   download="firefox-39-installer.exe">
  Download Firefox 39 for Windows
</a>

Active learning: creating a navigation menu

For this exercise, we'd like you to link some pages together with a navigation menu to create a multi-page website. This is one common way in which a website is created — the same page structure is used on every page, including the same navigation menu, so when links are clicked it gives the impression that you are staying in the same place, and different content is being brought up.

You'll need to make local copies of the following four pages, in the same directory as one another (see the navigation-menu-start directory if you want a the full listing):

You should:

  1. Add an unordered list in the indicated place on one page, containing the names of the pages to link to. A navigation menu is usually just a list of links, so this is semantically ok.
  2. Turn each page name into a link to that page.
  3. Copy the navigation menu across to each page.
  4. On each page, remove just the link to that same page — it is confusing and pointless for a page to include a link to itself, and the lack of a link acts a good visual reminder of what page you are currently on.

The finished example should end up looking something like this:

An example of a simple HTML navigation menu, with home, pictures, projects, and social menu items

Note: If you get stuck, or are not sure if you have got it right, you can check the navigation-menu-marked-up directory to see the correct answer.

It is possible to create links or buttons that, when clicked, open a new outgoing email message rather than linking to a resource or page. This is done using the <a> element and the mailto: URL scheme.

In its most basic and commonly used form, a mailto: link simply indicates the email address of the intended recipient. For example:

<a href="mailto:nowhere@mozilla.org">Send email to nowhere</a>

This results in a link that looks like this: Send email to nowhere.

In fact, the email address is even optional. If you leave it out (that is, your href is simply "mailto:"), a new outgoing email window will be opened by the user's mail client that has no destination address specified yet. This is often useful as "Share" links that users can click to send an email to an address of their choosing.

Specifying details

In addition to the email address, you can provide other information. In fact, any standard mail header fields can be added to the mailto URL you provide. The most commonly used of these are "subject", "cc", and "body" (which is not a true header field, but allows you to specify a short content message for the new email). Each field and its value is specified as a query term.

Here's an example that includes a cc, bcc, subject and body:

<a href="mailto:nowhere@mozilla.org?cc=name2@rapidtables.com&bcc=name3@rapidtables.com&amp;subject=The%20subject%20of%20the%20email &amp;body=The%20body%20of%20the%20email">
  Send mail with cc, bcc, subject and body
</a>

Note: The values of each field must be URL-encoded (that is, with non-printing characters and spaces percent-escaped). Also note the use of the ampersand (&) to separate each field in the mailto: URL. This is standard URL query notation.

Here are a few other sample mailto URLs:

Summary

That's it for links, for now anyway! You'll return to links later on in the course when you start to look at styling them. Next up for HTML, we'll return to text semantics and look at some more advanced/unusual features that you'll find useful — Advanced text formatting is your next stop.