MDN wants to learn about developers like you: https://qsurvey.mozilla.com/s3/MDN-dev-survey

현재 번역은 완벽하지 않습니다. 한국어로 문서 번역에 동참해주세요.

앞으로 여기서는 HTML의 기본에 대해서 다룰 것입니다. 시작에 앞서, 기본원리, 속성 그리고, 이전에 들어봤을 중요한 것들을 HTML에 적합하게 소개할 것입니다. 또한 HTML의 요소들이 어떻게 구성되고, 어떻게 HTML 웹페이지가 짜여져 있는지, 기본적인 언어의 중요한 특징들을 설명할 것입니다. 흥미를 높이고자 수업 중간에 HTML을 사용하서 재밌는 것도 만들어볼 것입니다.

알아야 할 것 기본적인 컴퓨터의 이해, basic software installedworking with files의 기본적 지식.
목표 HTML언어에 대해 익숙해지고, HTML을 이용하여 실습해봅니다.

HTML이란?

HTML (Hypertext Markup Language,하이퍼텍스트 마크업 언어)는 프로그래밍 언어는 아니고, 우리가 보는 웹페이지가 어떻게 구조화되어 있는지 브라우저로 하여금 알 수 있도록 하는 마크업 언어입니다. 이는 개발자로 하여금 복잡하게도 간단하게도 프로그래밍 할 수 있습니다. HTML은 elements로 구성되어 있으며, 이들은 적절한 방법으로 나타내고 실행하기 위해 각 컨텐츠의 여러 부분들을 감싸고 마크업 합니다. tags 는 웹 상의 다른 페이지로 이동하게 하는 하이퍼링크 내용들을 생성하거나, 단어를 강조하는 등의 역할을 합니다.  예를들어, 다음의 내용을 봅시다.

My cat is very grumpy

만약 다음의 문장을 그냥 그 자체로 표시하고 싶다면, 태그 중  (<p>)로 감싸 엘리먼트를 문단으로 명시할 수 있습니다.

<p>My cat is very grumpy</p>

HTML 요소(Element)의 구조

HTML에서의 요소에 대해 좀 더 알아봅시다.

엘리먼트의 주요 부분은 다음과 같습니다.

  1. The opening tag: 이것은 요소의 이름과(이 경우 p), 열고 닫는 꺽쇠 괄호로 구성됩니다. 요소가 시작(이 경우 단락의 시작 부분)부터 효과가 적용되기 시작합니다.
    The closing tag: 이것은 요소의 이름 앞에 슬래시(/)가 있는것을 제외하면 여는 태그(opening tag)와 같습니다. 이것은 요소의 끝(이 경우 단락의 끝 부분)에 위치합니다.  닫는 태그를 적어주지 않는 것은 흔한 초심자의 오류이며, 이것은 이상한 결과를 낳게됩니다.
  2. The content: 요소의 내용이며, 이 경우 단순한 텍스트이다.
  3. The element: 여는 태그, 닫는 태그, 내용을 통틀어 요소(element)라고한다.

실습: 첫 번째 HTML 요소 만들어보기

Edit the line below in the Input area by wrapping it with the tags <em> and </em> (put <em> before it to open the element, and </em> after it, to close the element) — this should give the line italic emphasis! You'll be able to see your changes update live in the Output area.

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 the answer.

Nesting elements

You can put elements inside other elements too — this is called nesting. If we wanted to state that our cat is VERY grumpy, we could wrap the word "very" in a <strong> element, which means that the word is to be strongly emphasized:

<p>My cat is <strong>very</strong> grumpy.</p>

You do however need to make sure that your elements are properly nested: in the example above we opened the p element first, then the strong element, therefore we have to close the strong element first, then the p. The following is incorrect:

<p>My cat is <strong>very grumpy.</p></strong>

The elements have to open and close correctly so they are clearly inside or outside one another. If they overlap like above, then your web browser will try to make a best guess at what you were trying to say, and you may well get unexpected results. So don't do it!

Block versus inline elements

There are two important categories of elements in HTML, which you should know about — block level elements and inline elements.

  • Block level elements form a visible block on a page — they will appear on a new line from whatever content went before it, and any content that goes after it will also appear on a new line. Block level elements tend to be structural elements on the page that represent e.g. paragraphs, lists, navigation menus, footers, etc. A block level element wouldn't be nested inside an inline element, but it might be nested inside another block level element.
  • Inline elements are those that are contained within block level elements and surround only small parts of the document’s content, not entire paragraphs and groupings of content. An inline element will not cause a new line to appear in the document: they would normally appear inside a paragraph of text, for example an <a> element (hyperlink) or emphasis elements such as <em> or <strong>.

Take the following example:

<em>first</em><em>second</em><em>third</em>

<p>fourth</p><p>fifth</p><p>sixth</p>

<em> is an inline element, so as you can see below, the first three elements sit on the same line as one another with no space in between. <p> on the other hand is a block level element, so each element appears on a new line, with space above and below each (the spacing is due to default CSS styling that the browser applies to paragraphs).

Note: HTML5 redefined the element categories in HTML5: see Element content categories. While these definitions are more accurate and less ambiguous than the ones that went before, they are a lot more complicated to understand than "block" and "inline", so we will stick with these throughout this topic.

Note: You can find useful reference pages that include lists of block and inline elements — see Block-level elements and Inline elements.

Empty elements

Not all elements follow the above pattern of opening tag, content, closing tag. Some elements consist only of a single tag, which is usually used to insert/embed something in the document at the place it is included. For example, the <img> element inserts an image onto a page in the position it is included in:

<img src="https://raw.githubusercontent.com/mdn/beginner-html-site/gh-pages/images/firefox-icon.png">

This would output the following on your page:

Note: Empty elements are also sometimes called void elements.

Attributes

Elements can also have attributes, which look like this:

<p class="editor-note">My cat is very grumpy</p>

Attributes contain extra information about the element which you don't want to appear in the actual content. In this case, the class attribute allows you to give the element an identifying name that can be later used to target the element with style information and other things.

An attribute should have:

  1. A space between it and the element name (or the previous attribute, if the element already has one or more attributes.)
  2. The attribute name, followed by an equals sign.
  3. An attribute value, with opening and closing quote marks wrapped around it.

Active learning: Adding attributes to an element

Another example of an element is <a> — this stands for anchor, and will make the piece of text it wraps around into a hyperlink. This can take a number of attributes, but two are as follows:

  • href: This attribute specifies as its value the web address that you want the link to point to; where the browser navigates to when the link is clicked. For example, href="https://www.mozilla.org/".
  • title: The title attribute specifies extra information about the link, such as what the page is that you are linking to. For example, title="The Mozilla homepage". This will appear as a tooltip when hovered over.

Edit the line below in the Input area to turn it into a link to your favourite website. First, add the <a> element, then the href attribute, then the title attribute. You'll be able to see your changes update live in the Output area. You should see a link that when hovered over displays the title attribute's content, and when clicked navigates to the web address in the href element. Remember that you need to include a space between the element name, and each attribute.

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 the answer.

Boolean attributes

You'll sometimes see attributes written without values — this is perfectly allowed. These are called boolean attributes, and they can only have one value, which is generally the same as the attribute name. As an example, take the disabled attribute, which you can assign to form input elements if you want them to be disabled (greyed out) so the user can't enter any data in them.

<input type="text" disabled="disabled">

As shorthand, it is perfectly allowable to write this as follows (we've also included a non-disabled form input element for reference, to give you more of an idea what is going on):

<input type="text" disabled>

<input type="text">

Both will give you an output as follows:

Omitting quotes around attribute values

When you look around the World Wide Web, you'll come across all kind of strange markup styles, including attribute values without quotes. This is allowable in certain circumstances, but will break your markup in others. For example, if we revisit our link example from earlier, we could write a basic version with only the href attribute, like this:

<a href=https://www.mozilla.org/>favourite website</a>

However, as soon as we add the title attribute in this style, things will go wrong:

<a href=https://www.mozilla.org/ title=The Mozilla homepage>favourite website</a>

At this point the browser will misinterpret your markup, thinking that the title attribute is actually three attributes — a title attribute with the value "The", and two boolean attributes, Mozilla and homepage. This is obviously not what was intended, and will cause errors or unexpected behaviour in the code, as seen in the live example below. Try hovering over the link to see what the title text is!

Our advice is to always include the attribute quotes — it avoids such problems, and results in more readable code too.

Single or double quotes?

In this article you'll notice that the attributes are all wrapped in double quotes. You might however see single quotes in some people's HTML. This is purely a matter of style, and you can feel free to chose which one you prefer. Both the following lines are equivalent:

<a href="http://www.example.com">A link to my example.</a>

<a href='http://www.example.com'>A link to my example.</a>

You should however make sure you don't mix them together. The following will go wrong!

<a href="http://www.example.com'>A link to my example.</a>

If you've used one type of quote in your HTML, you can nest the other type of quote:

<a href="http://www.example.com" title="Isn't this fun?">A link to my example.</a>

If you want to nest the same type of quote, you'll have to use Entity references: including special characters in HTML.

Anatomy of an HTML document

That wraps up the basics of individual HTML elements, but they aren't very useful on their own. Now we'll look at how individual elements are combined to form an entire HTML page:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <title>My test page</title>
  </head>
  <body>
    <p>This is my page</p>
  </body>
</html>

Here we have:

  1. <!DOCTYPE html>: The doctype. In the mists of time, when HTML was young (about 1991/2), doctypes were meant to act as links to a set of rules that the HTML page had to follow to be considered good HTML, which could mean automatic error checking and other useful things. They used to look something like this:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    However, these days no-one really cares about them, and they are really just a historical artifact that needs to be included for everything to work right. <!DOCTYPE html> is the shortest string of characters that counts as a valid doctype; that's all you really need to know.
  2. <html></html>: The <html> element. This element wraps all the content on the entire page, and is sometimes known as the root element.
  3. <head></head>: The <head> element. This element acts as a container for all the stuff you want to include on the HTML page that isn't the content you are showing to your page's viewers. This includes things like keywords and a page description that you want to appear in search results, CSS to style our content, character set declarations, and more. You'll learn more about this in the next article in the series.
  4. <meta charset="utf-8">: This element sets the character set your document should use to utf-8, which includes most characters from all known human languages. Essentially it can now handle any textual content you might put on it. There is no reason not to set this, and it can help avoid some problems later on.
  5. <title></title>: This sets the title of your page, which is the title that appears in the browser tab the page is loaded in, and is used to describe the page when you bookmark/favourite it.
  6. <body></body>: The <body> element. This contains all the content that you want to show to web users when they visit your page, whether that's text, images, videos, games, playable audio tracks, or whatever else.

Active learning: Adding some features to an HTML document

If you want to experiment with writing some HTML on your local computer, you can:

  1. Copy the HTML page example listed above.
  2. Create a new file in your text editor.
  3. Paste the code into the new text file.
  4. Save the file as index.html.

Note: You can also find this basic HTML template on the MDN Learning Area Github repo.

You can now open this file in a web browser to see what the rendered code looks like, and then edit the code and refresh the browser to see what the result is. Initially it will look like this:

A simple HTML page that says This is my pageSo in this exercise, you can edit the code locally on your computer, as outlined above, or you can edit it in the editable sample window below (the editable sample window represents just the contents of the <body> element, in this case.) We'd like you to have a go at implementing the following steps:

  • Just below the opening <body> tag, add a main title for the document. This should be wrapped inside an <h1> opening tag and </h1> closing tag.
  • Edit the paragraph content to include some text about something you are interested in.
  • Make any important words stand out in bold by wrapping them inside a <strong> opening tag and </strong> closing tag
  • Add a link to your paragraph, as explained earlier in the article.
  • Add an image to your document, below the paragraph, as explained earlier in the article. You'll get bonus points if you manage to link to a different image (either locally on your computer, or somewhere else on the Web.)

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 the answer.

Whitespace in HTML

In the above examples you may have noticed that a lot of whitespace is included in the code listings — this is not necessary at all; the two following code snippets are equivalent:

<p>Dogs are silly.</p>

<p>Dogs        are
         silly.</p>

No matter how much whitespace you use (which can include space characters, but also line breaks), the HTML parser reduces each one down to a single space when rendering the code. So why use so much whitespace? The answer is readability — it is so much easier to understand what is going on in your code if you have it nicely formatted, and not just bunched up together in a big mess. In our HTML we've got each nested element indented by two spaces more than the one it is sitting inside. It is up to you what style of formatting you use (how many spaces for each level of indentation, for example), but you should consider using some kind of formatting.

Entity references: including special characters in HTML

In HTML, the characters <, >,",' and & are special characters. They are parts of the HTML syntax itself, so how do you include one of these characters in your text, for example if you really want to use an ampersand or less than sign, and not have it interpreted as code as some browsers may do?

We have to use character references — special codes that represent characters, and can be used in these exact circumstances. Each character reference is started with an ampersand (&), and ended by a semi-colon (;).

Literal character Character reference equivalent
< &lt;
> &gt;
" &quot;
' &apos;
& &amp;

In the below example, you can see two paragraphs, which are talking about web technologies:

<p>In HTML, you define a paragraph using the <p> element.</p>

<p>In HTML, you define a paragraph using the &lt;p&gt; element.</p>

In the live output below, you can see that the first paragraph has gone wrong, because the browser thinks that the second instance of <p> is starting a new paragraph. The second paragraph looks fine, because we have replaced the angle brackets with character references.

Note: A chart of all the available HTML character entity references can be found on Wikipedia: List of XML and HTML character entity references.

HTML comments

In HTML, as with most programming languages, there is a mechanism available to write comments in the code — comments are ignored by the browser and invisible to the user, and their purpose is to allow you to include comments in the code to say how your code works, what the different parts of the code do, etc. This can be very useful if you return to a code base that you've not worked on for 6 months, and can't remember what you did — or if you hand your code over to someone else to work on.

To turn a section of content inside your HTML file into a comment, you need to wrap it in the special markers <!-- and -->, for example:

<p>I'm not inside a comment</p>

<!-- <p>I am!</p> -->

As you can see below, the first paragraph appears in the live output, but the second one doesn't.

Summary

You've reached the end of the article — hope you enjoyed your tour of the very basics of HTML. At this point you should understand what the language looks like, how it works at a basic level, and be able to write a few elements and attributes. This is a perfect place to be right now, as in subsequent articles in the module we will go into some of the things you have already looked at in a lot more detail, and introduce some new features of the language. Stay tuned!

Note: At this point, as you start to learn more about HTML, you might also want to start to explore the basics of Cascading Style Sheets, or CSS. CSS is the language you use to style your web pages (whether e.g. changing the font or colors, or altering the page layout.) HTML and CSS go very well together, as you'll soon discover.

문서 태그 및 공헌자

 이 페이지의 공헌자: takeU, ChanghwaLee
 최종 변경: takeU,