4. HTML Elements
What you will learn
- The difference between a tag and an element
- How to nest elements correctly
- What empty (void) elements are
- Block and inline elements
Tags and elements
An HTML element is the opening tag, the content, and the closing tag, taken together.
Example
<p>Learning is fun.</p>
| Part | In the example |
|---|---|
| Opening tag | <p> |
| Content | Learning is fun. |
| Closing tag | </p> |
| Element | All three together |
Nested elements
Elements can sit inside other elements. This is called nesting. The inner element must be closed before the outer one.
Correct nesting
<p>This is <em>very</em> useful.</p>
Output
This is very useful.
Wrong nesting (do not do this)
<p>This is <em>very</p></em>
Here <p> is closed while <em> is still open. Browsers try to guess what you meant, but the result can be unpredictable.
Empty elements
Some elements have no content and no closing tag. They are called empty or void elements. Common ones are <br> (line break), <hr> (horizontal line), and <img> (image).
Example
<p>First line<br>Second line</p>
<hr>
Output
First line
Second line
Block and inline elements
- Block elements start on a new line and take the full width, for example
<p>,<div>, and headings. - Inline elements stay within a line of text, for example
<strong>,<em>, and<a>.
Case and whitespace
Tag names are not case sensitive, but the standard practice is lowercase. Browsers also collapse extra spaces and line breaks into one space, so adding blank lines in your code does not add blank lines on the page.
Common mistakes
- Closing elements in the wrong order.
- Forgetting a closing tag on elements that need one.
- Putting a block element such as
<p>inside an inline element such as<em>. - Pressing Enter several times and expecting extra space on the page.
Exercise
Write a paragraph that says Coding is rewarding, with the word rewarding emphasized, followed by a horizontal line.
Show solution
<p>Coding is <em>rewarding</em></p>
<hr>
Knowledge check
1. What three parts make up an HTML element?
An opening tag, content, and a closing tag.
2. Name an empty element.
<br>, <hr>, or <img>.
3. Is <strong> a block or inline element?
Inline.
Summary
- An element is an opening tag, content, and closing tag.
- Close nested elements in reverse order.
- Empty elements have no content or closing tag.
- Block elements take their own line. Inline elements flow within text.
Next lesson: HTML Attributes.