HTML elements – The basics
An HTML element is is a piece of content (usually text) that is enclosed within tags. The tag name defines what type of content it is and how it should be displayed.
<h1></h1>
Defines a Heading
<p></p>
Defines a paragraph
<a href="#"></a>
Defines an anchor link
Most HTML elements have an opening, and closing tag, the content sitting between them, for example:
<h1>This is a heading</h1>
<p>This is my first paragraph</p>
however, there are a few tags that don't have a closing tag. for example:
<br> This is used to insert a line break.
<hr> This with insert a horizontal rule.
<img src="https://images.unsplash.com/photo-1596854407944-bf87f6fdd49e" alt="ginger cat">
the img
tag is used to insert an image.
Attributes
Attributes are often included in an HTML open tag to define more information about the content. Attributes are included using a name and value pair. In the examples below the attribute href for "hypertext reference", defines the location the anchor link should go when the text "visit google" is clicked.
<a href="https://google.com">visit google</a>
in this image element:
<img src="https://images.unsplash.com/photo-1596854407944-bf87f6fdd49e" alt="ginger cat">
the scr
or "source" attribute is used to define the location of the images to display. The alt
attribute defines alternate text for when the image cannot be displayed or viewed. alt attributes are important for the accessibility of visually impaired readers.
another common attribute that is often included in an HTML tag is class
. class
attributes make it possible to differentiate different types of content with the same tags and style them accordingly in CSS.
the id
attribute is used to define a unique identifier for an HTML element. This makes the element easy to select using javascript and can be navigated to using anchor links.
Block vs inline
The browser has two ways to display elements in the viewport.
Block elements always start on a new line and use the full width of the viewport.
Examples of block level elements include:
<p>
<ol>
,<ul>
,<dl>
- All headings
h1
–h6
<article>
,<section>
,<div>
Inline elements display in a line. They do not force the text after them to a new line.
An anchor (or link) is an example of an inline element. You can put several links in a row, and they will display in a line.
Examples of inline elements:
<a>
<strong>
,<em>
,<b>
,<i>
,<q>, <mark>
<span>
The img
tag is also an example of an inline element, meaning that unless they are floated (covered later in CSS) they will flow horizontally with text and other inline elements.
Take a look at the codepen below, notice that each of the paragraph tags are presented as a block and the anchor tag stays inline.
Try moving the img tag inside one of the paragraph tags. What do you think will happen?
Did you notice that the image can sit between words in the paragraph?
the default display properties of an element can be changed using CSS styles.