HTML의 이미지

처음에는 웹에 텍스트만 있었고 조금 지루했습니다. 다행히도 웹 페이지 안에 이미지 (및 보다 흥미로운 유형의 컨텐츠)를 삽입하는 기능이 추가되기까지는 오래 걸리지 않았습니다. 시작해볼 수 있는 다른 유형의 멀티미디어가 있지만 단순한 이미지를 웹 페이지에 삽입하는 데 사용되는 <img> 요소로 쉽게 시작해 보겠습니다. 이 글에서는 기초내용 부터 심층적으로 사용하는 방법, <figure>를 사용하여 캡션을 주석으로 추가하는 방법, <css>배경 이미지와 관련된 사용 방법을 자세히 설명합니다.

선행사항: 기본 컴퓨터 활용 능력, 기본 소프트웨어 설치파일작업에 대한 기본 지식, HTML 기초 지식 익숙 (HTML 시작하기에서 설명)
목표: 간단한 이미지를 HTML에 삽입하고, 캡션을 사용하여 주석을 추가하는 방법과 HTML 이미지가 CSS 배경 이미지와 관련되는 방법을 배우십시오.

웹페이지에 어떻게 이미지를 넣을까?

이미지를 웹사이트에 넣기위해서 <img> 요소를 사용합니다. 이것은 텍스트 내용이나 클로징 태그를 갖지 않는 비어있는 요소 (empty element)이며, 적어도 src(풀네임인 source라고 불리곤 합니다)라는 속성 하나는 사용되어야합니다. src 속성은 당신이 페이지에 삽입하고자 하는 이미지를 가리키는 경로를 포함합니다. 그 경로는 <a> 요소의 href 속성 값처럼 상대경로여도, 절대경로여도 됩니다.

노트: 계속하기 전에 절대경로, 상대경로에 대해 복습하기 위해  A quick primer on URLs and paths를 읽어보세요.

예를 들어, 당신의 이미지 파일 이름이 dinosaur.jpg 이고, 당신의 HTML 페이지와 같은 디렉토리 아래에 위치한다면 이런 식으로 이미지를 삽입할 수 있습니다:

<img src="dinosaur.jpg">

그 이미지가 HTML페이지와 같은 디렉토리 하의 images 라는 하위 디렉토리에 있다면 (이러한 방식은 구글이 SEO/색인을 위해 추천합니다), 이런 식으로 삽입할 수 있습니다:

<img src="images/dinosaur.jpg">

노트: 검색 엔진은 이미지 파일 이름을 읽고 SEO에 포함시킵니다. 따라서 그 내용을 기술하는 파일 이름을 사용하세요. img835.png.보다는 dinosaur.jpg 가 낫습니다.

절대경로를 사용해서 이미지를 삽입할 수도 있습니다. 예를 들면: 

<img src="https://www.example.com/images/dinosaur.jpg">

그러나 이건 무의미합니다. DNS 서버로부터 IP 주소를 처음부터 다시 찾아보는 등 브라우저가 더 많은 일을 하게 만들기 때문입니다. 당신은 거의 항상 당신의 HTML과 같은 서버에 이미지를 두게 될 것입니다.

주의사항: 대부분의 이미지들은 저작권 적용 대상입니다. 따라서, 

1) 당신이 그 이미지에 대한 소유권을 갖고 있거나
2) 당신이 그 이미지의 소유자로부터 명확한 서류상의 허가를 받았거나
3) 그 이미지가 실제로 공공재라는 충분한 증거가 있는 경우

가 아니면 당신의 웹페이지에 이미지를 게시하지 마십시오. 

저작권 침해는 불법이며 비윤리적입니다. 또한 당신의 src 속성이 링크하도록 허가받지 않은 누군가의 웹사이트에 호스팅 된 이미지를 가리키지 않도록 하십시오. 이러한 행위를 "핫 링킹(hot linking)"이라고 합니다. 누군가의 대역폭을 훔쳐 쓰는 것은 불법입니다. 이것은 당신의 페이지를 느리게 만들고, 그 이미지가 삭제되거나 무언가 부끄러운 걸로 바뀌어도 당신은 그것을 통제할 권한이 없습니다.

위에서 쓴 우리의 코드는 이러한 결과를 보여줄 것입니다:

A basic image of a dinosaur, embedded in a browser, with "Images in HTML" written above it

Note: Elements like <img> and <video> are sometimes referred to as replaced elements. This is because the element's content and size are defined by an external resource (like an image or video file), not by the contents of the element itself.

Note: You can find the finished example from this section running on Github (see the source code too.)

Alternative text

The next attribute we'll look at is alt. Its value is supposed to be a textual description of the image, for use in situations where the image cannot be seen/displayed. For example, our above code could be modified like so:

<img src="images/dinosaur.jpg"
     alt="The head and torso of a dinosaur skeleton;
          it has a large head with long sharp teeth">

The easiest way to test your alt text is to purposely misspell your filename. If for example our image name was spelled dinosooooor.jpg, the browser wouldn't display the image, and display the alt text instead:

The Images in HTML title, but this time the dinosaur image is not displayed, and alt text is in its place.

So, why would you ever see or need alt text? It can come in handy for a number of reasons:

  • The user is visually impaired, and using a screen reader to read the web out to them. In fact, having alt text available to describe images is useful to most users.
  • As described above, you might have spelled the file or path name wrong.
  • The browser doesn't support the image type. Some people still use text-only browsers, such as Lynx, which alternatively displays the alt text of images.
  • You may want to provide text for search engines to utilize. For example, search engines can match alt text with search queries.
  • Users have turned off images to reduce data transfer volume and distractions. This is especially common on mobile phones, and in countries where bandwidth is limited and expensive.

What exactly should you write inside your alt attribute? It depends on why the image is there in the first place. In other words, what you lose if your image doesn't show up:

  • Decoration. You should use CSS background images for decorative images, but if you must use HTML, add a blank alt="". If the image isn't part of the content, a screen reader shouldn't waste time reading it.
  • Content. If your image provides significant information, provide the same information in a brief alt text – or even better, in the main text which everybody can see. Don't write redundant alt text. How annoying would it be for a sighted user if all paragraphs were written twice in the main content? If the image is described adequately by the main text body, you can just use alt="".
  • Link. If you put an image inside <a> tags, to turn an image into a link, you still must provide accessible link text. In such cases you may, either, write it inside the same <a> element, or inside the image's alt attribute – whichever works best in your case.
  • Text. You should not put your text into images. If your main heading needs a drop shadow, for example, use CSS for that rather than putting the text into an image. However, If you really can't avoid doing this, you should supply the text inside the alt attribute.

Essentially, the key is to deliver a usable experience, even when the images can't be seen. This ensures all users are not missing any of the content. Try turning off images in your browser and see how things look. You'll soon realize how helpful alt text is if the image cannot be seen.

Note: For more information, see our guide to Text Alternatives.

Width and height

You can use the width and height attributes to specify the width and height of your image. You can find your image's width and height in a number of ways. For example on the Mac you can use Cmd + I to get the info display up for the image file. Returning to our example, we could do this:

<img src="images/dinosaur.jpg"
     alt="The head and torso of a dinosaur skeleton;
          it has a large head with long sharp teeth"
     width="400"
     height="341">

This doesn't result in much difference to the display, under normal circumstances. But if the image isn't being displayed, for example, the user has just navigated to the page, and the image hasn't yet loaded, you'll notice the browser is leaving a space for the image to appear in:

The Images in HTML title, with dinosaur alt text, displayed inside a large box that results from width and height settings

This is a good thing to do, resulting in the page loading quicker and more smoothly.

However, you shouldn't alter the size of your images using HTML attributes. If you set the image size too big, you'll end up with images that look grainy, fuzzy, or too small, and wasting bandwidth downloading an image that is not fitting the user's needs. The image may also end up looking distorted, if you don't maintain the correct aspect ratio. You should use an image editor to put your image at the correct size before putting it on your webpage.

Note: If you do need to alter an image's size, you should use CSS instead.

Image titles

As with links, you can also add title attributes to images, to provide further supporting information if needed. In our example, we could do this:

<img src="images/dinosaur.jpg"
     alt="The head and torso of a dinosaur skeleton;
          it has a large head with long sharp teeth"
     width="400"
     height="341"
     title="A T-Rex on display in the Manchester University Museum">

This gives us a tooltip, just like link titles:

The dinosaur image, with a tooltip title on top of it that reads A T-Rex on display at the Manchester University Museum

Image titles aren't essential to include. It is often better to include such supporting information in the main article text, rather than attached to the image. However, they are useful in some circumstances; for example, in an image gallery when you have no space for captions.

Active learning: embedding an image

It is now your turn to play! This active learning section will have you up and running with a simple embedding exercise. You are provided with a basic <img> tag; we'd like you to embed the image located at the following URL:

https://raw.githubusercontent.com/mdn/learning-area/master/html/multimedia-and-embedding/images-in-html/dinosaur_small.jpg

Earlier we said to never hotlink to images on other servers, but this is just for learning purposes, so we'll let you off this one time.

We would also like you to:

  • Add some alt text, and check that it works by misspelling the image URL.
  • Set the image's correct width and height (hint; it is 200px wide and 171px high), then experiment with other values to see what the effect is.
  • Set a title on the image.

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see an answer:

Annotating images with figures and figure captions

Speaking of captions, there are a number of ways that you could add a caption to go with your image. For example, there would be nothing to stop you doing this:

<div class="figure">
  <img src="images/dinosaur.jpg"
       alt="The head and torso of a dinosaur skeleton;
            it has a large head with long sharp teeth"
       width="400"
       height="341">

  <p>A T-Rex on display in the Manchester University Museum.</p>
</div>

This is ok. It contains the content you need, and is nicely stylable using CSS. But there is a problem here: there is nothing that semantically links the image to its caption, which can cause problems for screen readers. For example, when you have 50 images and captions, which caption goes with which image?

A better solution, is to use the HTML5 <figure> and <figcaption> elements. These are created for exactly this purpose: to provide a semantic container for figures, and clearly link the figure to the caption. Our above example could be rewritten like this:

<figure>
  <img src="images/dinosaur.jpg"
       alt="The head and torso of a dinosaur skeleton;
            it has a large head with long sharp teeth"
       width="400"
       height="341">

  <figcaption>A T-Rex on display in the Manchester University Museum.</figcaption>
</figure>

The <figcaption> element tells browsers, and assistive technology that the caption describes the other content of the <figure> element.

Note: From an accessibility viewpoint, captions and alt text have distinct roles. Captions benefit even people who can see the image, whereas alt text provides the same functionality as an absent image. Therefore, captions and alt text shouldn't just say the same thing, because they both appear when the image is gone. Try turning images off in your browser and see how it looks.

A figure doesn't have to be an image. It is an independent unit of content that:

  • Expresses your meaning in a compact, easy-to-grasp way.
  • Could go in several places in the page's linear flow.
  • Provides essential information supporting the main text.

A figure could be several images, a code snippet, audio, video, equations, a table, or something else.

Active learning: creating a figure

In this active learning section, we'd like you to take the finished code from the previous active learning section, and turn it into a figure:

  • Wrap it in a <figure> element.
  • Copy the text out of the title attribute, remove the title attribute, and put the text inside a <figcaption> element below the image.

If you make a mistake, you can always reset it using the Reset button. If you get really stuck, press the Show solution button to see an answer:

CSS background images

You can also use CSS to embed images into webpages (and JavaScript, but that's another story entirely). The CSS background-image property, and the other background-* properties, are used to control background image placement. For example, to place a background image on every paragraph on a page, you could do this:

p {
  background-image: url("images/dinosaur.jpg");
}

The resulting embedded image, is arguably easier to position and control than HTML images. So why bother with HTML images? As hinted to above, CSS background images are for decoration only. If you just want to add something pretty to your page to enhance the visuals, this is fine. Though, such images have no semantic meaning at all. They can't have any text equivalents, are invisible to screen readers, etc. This is HTML images time to shine!

Summing up: if an image has meaning, in terms of your content, you should use an HTML image. If an image is purely decoration, you should use CSS background images.

Note: You'll learn a lot more about CSS background images in our CSS topic.

That's all for now. We have covered images and captions in detail. In the next article we'll move it up a gear, looking at how to use HTML to embed video and audio in web pages.

In this module