Description and Basic Syntax
HTML (HyperText Markup Language) is the standard markup language for creating web pages and web applications. It provides the semantic structure and content of web documents, serving as the foundation upon which CSS and JavaScript build.
- Declarative Language: Describes what should be displayed, not how to compute it 
- Semantic Markup: Elements convey meaning about their content 
- Tree Structure: Nested elements form a Document Object Model (DOM) 
- Fault-Tolerant: Browsers attempt to render even malformed HTML 
HTML terminology
Tags
Tags are the building blocks of HTML that define how content should be structured and displayed. They are keywords wrapped in angle brackets < >.
<!-- Opening and closing tags -->
<p>This is a paragraph</p>
<!-- Self-closing tags (void elements) -->
<img src="image.jpg" alt="Description">
<br>
<hr>
<input type="text">
<meta charset="UTF-8">
<link rel="stylesheet" href="styles.css">HTML tags come in two types. Opening and closing tags like <p>...</p> wrap around content to define its purpose. Self-closing tags like <img>, <br>, and <hr> don't need a closing tag because they represent single elements without content inside them. These are also called void elements.
Common tags by category:
- Structural: - <html>,- <head>,- <body>
- Text: - <p>,- <h1>...- <h6>,- <span>,- <strong>,- <em>
- Container: - <div>,- <section>,- <article>,- <main>
- Lists: - <ul>,- <ol>,- <li>,- <dl>,- <dt>,- <dd>
- Media: - <img>,- <video>,- <audio>,- <picture>
- Interactive: - <a>,- <button>,- <form>,- <input>
Elements
Elements are complete HTML components consisting of:
- Opening tag 
- Content (optional) 
- Closing tag (unless self-closing) 
Elements can be nested to create complex document structures:
<article>
  <header>
    <h1>Article Title</h1>
    <time datetime="2024-01-15">January 15, 2024</time>
  </header>
  <p>Article content goes here...</p>
</article>HTML elements can be placed inside each other to create structured documents. An article contains a header, which itself contains a heading and time element, plus a paragraph. This nesting creates a tree-like hierarchy that browsers use to render the page.
Attributes
Attributes provide additional information about elements. They appear in the opening tag as name/value pairs:
<!-- Global attributes (work on any element) -->
<div id="unique-id" class="container active" data-user-id="123">
  <p title="Tooltip text" style="color: blue;" hidden>Content</p>
</div>
<!-- Element-specific attributes -->
<a href="https://example.com" target="_blank" rel="noopener">Link</a>
<img src="photo.jpg" alt="Description" width="300" height="200" loading="lazy">
<input type="email" required placeholder="Enter email" pattern="[^ @]*@[^ @]*">Attributes provide additional information about HTML elements and appear inside the opening tag as name-value pairs. Global attributes like id, class, and data-* work on any element. Element-specific attributes like href for links or src for images only apply to certain tags.
Essential Global Attributes:
- id- Unique identifier
- class- CSS styling hooks (space-separated list)
- data-*- Custom data attributes for JavaScript
- style- Inline CSS (use sparingly)
- title- Tooltip text
- lang- Language specification
- dir- Text direction (ltr/rtl)
- hidden- Hide element
- tabindex- Tab order for keyboard navigation
- contenteditable- Make content editable

The complete HTML5 document structure
<!DOCTYPE html>
<html lang="en">
<head>
  <!-- Metadata about the HTML document -->
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta name="description" content="Page description for SEO">
  <meta name="keywords" content="html, web, development">
  <meta name="author" content="Your Name">
  
  <!-- Open Graph tags for social media -->
  <meta property="og:title" content="Page Title">
  <meta property="og:description" content="Page description">
  <meta property="og:image" content="https://example.com/image.jpg">
  
  <title>Page Title - Site Name</title>
  
  <!-- External resources -->
  <link rel="stylesheet" href="css/styles.css">
  <link rel="icon" type="image/x-icon" href="/favicon.ico">
  <link rel="preconnect" href="https://fonts.googleapis.com">
  
  <!-- Preload critical resources -->
  <link rel="preload" href="font.woff2" as="font" crossorigin>
  
  <!-- This is a comment and will be ignored by the browser -->
</head>
<body>
  <!-- Page content goes here -->
  <header>
    <nav><!-- Navigation menu --></nav>
  </header>
  
  <main>
    <h1>Main Heading</h1>
    <p>Content...</p>
  </main>
  
  <footer>
    <p>© 2024 Company Name</p>
  </footer>
  
  <!-- JavaScript at the end for better performance -->
  <script src="js/script.js"></script>
</body>
</html>Every HTML page needs a standard skeleton structure. The <!DOCTYPE html> declaration identifies the document type. The <head> section contains metadata, character encoding, viewport settings, SEO information, and links to external resources. The <body> contains all visible content organized with semantic elements.
Important Meta tags for modern web apps:
<!-- Responsive design -->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Theme color for mobile browsers -->
<meta name="theme-color" content="#4285f4">
<!-- Prevent search engine indexing (for development) -->
<meta name="robots" content="noindex, nofollow">
<!-- Refresh page after 30 seconds -->
<meta http-equiv="refresh" content="30">
<!-- Content Security Policy -->
<meta http-equiv="Content-Security-Policy" content="default-src 'self'">Meta tags control browser and search engine behavior without appearing on the page. The viewport tag enables responsive design on mobile devices. Theme-color sets the browser toolbar color on mobile. Robots controls search engine indexing. Refresh auto-reloads pages. Content-Security-Policy enhances security by restricting resource loading.
Divisions and Spans
Container elements that have no semantic meaning on their own, used primarily for styling and JavaScript manipulation:
<!-- div: Block-level generic container -->
<div class="container">
  <div class="row">
    <div class="column">Content</div>
  </div>
</div>
<!-- span: Inline generic container -->
<p>This is <span class="highlight">highlighted</span> text.</p>
<!-- Modern semantic alternatives (prefer these when appropriate) -->
<main>     <!-- Main content -->
<section>  <!-- Thematic grouping -->
<article>  <!-- Self-contained content -->
<aside>    <!-- Sidebar content -->
<nav>      <!-- Navigation -->
<header>   <!-- Introductory content -->
<footer>   <!-- Footer content --><div> creates block-level containers that take full width and start on new lines. <span> creates inline containers that only take up as much space as their content. Both are generic containers without semantic meaning, primarily used for styling or JavaScript manipulation. Modern semantic alternatives like <main>, <section>, and <article> should be preferred when they match the content's purpose.
Linking Between Pages and Resources
Creating Hyperlinks
The <a> (anchor) element creates hyperlinks to other pages, files, locations within the same page, email addresses, or any other URL:
<!-- External link (absolute URL) -->
<a href="https://www.example.com">Visit Example.com</a>
<!-- Internal link (relative URL) -->
<a href="/about.html">About Us</a>
<a href="../products/item.html">Product Details</a>
<!-- Same page navigation (fragment identifier) -->
<a href="#section2">Jump to Section 2</a>
<h2 id="section2">Section 2</h2>
<!-- Email link -->
<a href="mailto:contact@example.com">Send Email</a>
<!-- Phone link (mobile-friendly) -->
<a href="tel:+1234567890">Call Us</a>
<!-- Download link -->
<a href="/files/document.pdf" download>Download PDF</a>
<!-- Open in new tab (with security) -->
<a href="https://external.com" target="_blank" rel="noopener noreferrer">
  External Link
</a>
<!-- Link with multiple attributes -->
<a href="https://example.com" 
   title="Visit our partner site"
   target="_blank"
   rel="noopener noreferrer"
   class="external-link"
   data-track="partner-link">
  Partner Site
</a>The <a> (anchor) element creates clickable links to other pages, sections, emails, or phone numbers. External links use absolute URLs, internal links use relative paths. Fragment identifiers starting with # jump to sections on the same page. The target="_blank" attribute opens links in new tabs. Always include rel="noopener noreferrer" for security when opening external sites.
Link Best Practices:
- Use descriptive link text (avoid "click here") 
- Include - rel="noopener noreferrer"for- target="_blank"links (security)
- Use relative URLs for internal links (maintainability) 
- Consider adding - titleattributes for additional context
Adding Media
Images
<!-- Basic image -->
<img src="photo.jpg" alt="Descriptive text for accessibility">
<!-- Responsive image with multiple sources -->
<picture>
  <source media="(min-width: 768px)" srcset="large.jpg">
  <source media="(min-width: 480px)" srcset="medium.jpg">
  <img src="small.jpg" alt="Responsive image">
</picture>
<!-- Lazy loading for performance -->
<img src="image.jpg" alt="Description" loading="lazy">
<!-- Image with dimensions (prevents layout shift) -->
<img src="photo.jpg" alt="Description" width="800" height="600">
<!-- Using figure for captioned images -->
<figure>
  <img src="chart.png" alt="Sales chart">
  <figcaption>Q4 2024 Sales Performance</figcaption>
</figure>Images are embedded using the <img> tag with required src and alt attributes. The <picture> element enables responsive images that adapt to screen size. The loading="lazy" attribute improves performance by deferring offscreen images. Setting explicit width and height prevents layout shift during page loading. The <figure> and <figcaption> elements semantically group images with their captions.
Video and Audio
<!-- Video with controls and multiple sources -->
<video controls width="640" height="360" poster="thumbnail.jpg">
  <source src="video.mp4" type="video/mp4">
  <source src="video.webm" type="video/webm">
  <p>Your browser doesn't support HTML video.</p>
</video>
<!-- Audio element -->
<audio controls>
  <source src="audio.mp3" type="audio/mpeg">
  <source src="audio.ogg" type="audio/ogg">
</audio>HTML5 provides native media support without plugins. The <video> and <audio> elements accept multiple <source> children with different file formats, allowing browsers to choose supported formats. The controls attribute adds playback controls. Fallback content inside the media tags appears in browsers without HTML5 support.
Background Images (CSS)
While not HTML, background images are commonly set via CSS:
.hero {
  background-image: url('background.jpg');
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}Background images are set using CSS properties rather than HTML. The background-size: cover property scales images to fill containers. The background-position: center property centers images. The background-repeat: no-repeat property prevents tiling. These properties are commonly used for hero sections and decorative backgrounds.
Display Types: Block vs. Inline vs. Inline-block
Understanding how elements display is crucial for layout control:
Block Elements
Characteristics:
- Start on a new line 
- Occupy full width available 
- Stack vertically 
- Respect all margin and padding values 
- Can contain other block and inline elements 
<!-- Common block elements -->
<div>Division</div>
<p>Paragraph</p>
<h1>Heading</h1>
<section>Section</section>
<article>Article</article>
<header>Header</header>
<footer>Footer</footer>
<main>Main content</main>
<form>Form</form>
<ul><li>List item</li></ul>
<table>Table</table>
<blockquote>Quote</blockquote>Inline Elements
Characteristics:
- Flow within text content 
- Only occupy necessary width 
- Don't force line breaks 
- Ignore top/bottom margins 
- Vertical padding may overlap other lines 
- Cannot contain block elements 
<!-- Common inline elements -->
<span>Span text</span>
<a href="#">Link</a>
<strong>Bold text</strong>
<em>Italic text</em>
<code>Code snippet</code>
<img src="icon.png" alt="Icon">
<button>Button</button>
<input type="text">
<label>Label</label>
<small>Small text</small>
<mark>Highlighted</mark>Inline-block Elements
Characteristics:
- Flow inline like text 
- Respect width and height 
- Respect all margins and paddings 
- Don't force line breaks 
<!-- Elements that default to inline-block -->
<button>Button</button>
<input type="text">
<select><option>Option</option></select>
<textarea>Text area</textarea>
<!-- Converting display type with CSS -->
<style>
  .card {
    display: inline-block;
    width: 200px;
    margin: 10px;
    vertical-align: top;
  }
</style>
<div class="card">Card 1</div>
<div class="card">Card 2</div>Inline-block elements combine inline flow with block dimensioning. They sit side-by-side like inline elements but accept width and height like blocks. Form elements like <button>, <input>, <select>, and <textarea> are naturally inline-block. Any element can be converted using CSS display: inline-block, useful for creating side-by-side cards or navigation buttons.
HTML5 Semantic Elements
Semantic elements clearly describe their meaning to both the browser and developer, improving:
- SEO: Search engines better understand content structure 
- Accessibility: Screen readers can navigate more effectively 
- Maintainability: Code is self-documenting 
- Styling: More specific CSS targeting 
Common Semantic Elements
<header>
  <!-- Page or section header -->
  <nav>
    <!-- Navigation menu -->
    <ul>
      <li><a href="/">Home</a></li>
      <li><a href="/about">About</a></li>
    </ul>
  </nav>
</header>
<main>
  <!-- Main content (only one per page) -->
  <article>
    <!-- Self-contained content -->
    <header>
      <h1>Article Title</h1>
      <time datetime="2024-01-15">January 15, 2024</time>
    </header>
    
    <section>
      <!-- Thematic grouping -->
      <h2>Introduction</h2>
      <p>Content...</p>
    </section>
    
    <section>
      <h2>Main Points</h2>
      <p>More content...</p>
    </section>
    
    <footer>
      <p>Author: John Doe</p>
    </footer>
  </article>
  
  <aside>
    <!-- Sidebar, related content -->
    <h3>Related Articles</h3>
    <ul>
      <li><a href="#">Related Link 1</a></li>
    </ul>
  </aside>
</main>
<footer>
  <!-- Page footer -->
  <address>
    <!-- Contact information -->
    Contact us at <a href="mailto:info@example.com">info@example.com</a>
  </address>
  <small>© 2024 Company Name</small>
</footer>HTML5 semantic elements describe their purpose and content type. The <header> contains introductory content, <nav> holds navigation menus, <main> wraps primary content, <article> represents standalone content, <section> groups thematic content, <aside> holds sidebar content, and <footer> contains footer information. Using semantic tags instead of generic divs improves accessibility, SEO, and code readability.
Additional Semantic Elements
<!-- Details/Summary (collapsible content) -->
<details>
  <summary>Click to expand</summary>
  <p>Hidden content that appears when clicked</p>
</details>
<!-- Figure with caption -->
<figure>
  <img src="chart.png" alt="Sales chart">
  <figcaption>2024 Sales Performance</figcaption>
</figure>
<!-- Mark highlighted text -->
<p>Search results for <mark>HTML</mark> in the document.</p>
<!-- Progress bar -->
<progress value="70" max="100">70%</progress>
<!-- Dialog (modal) -->
<dialog id="myDialog">
  <p>This is a dialog box</p>
  <button onclick="myDialog.close()">Close</button>
</dialog>HTML5 provides specialized elements for specific purposes. The <details> and <summary> elements create collapsible sections with built-in functionality. The <figure> and <figcaption> elements semantically group images with captions. The <mark> element highlights text. The <progress> element displays progress bars. The <dialog> element creates modal dialogs.
Forms and Input Elements
Forms are crucial for user interaction in web applications:
<form action="/submit" method="POST" enctype="multipart/form-data">
  <!-- Text inputs -->
  <label for="name">Name:</label>
  <input type="text" id="name" name="name" required>
  
  <!-- Email with validation -->
  <input type="email" name="email" placeholder="email@example.com" required>
  
  <!-- Password -->
  <input type="password" name="password" minlength="8">
  
  <!-- Number input -->
  <input type="number" name="age" min="18" max="100" step="1">
  
  <!-- Date picker -->
  <input type="date" name="birthday" max="2024-12-31">
  
  <!-- File upload -->
  <input type="file" name="avatar" accept="image/*">
  
  <!-- Dropdown -->
  <select name="country">
    <option value="">Select a country</option>
    <option value="us">United States</option>
    <option value="uk">United Kingdom</option>
  </select>
  
  <!-- Radio buttons -->
  <input type="radio" id="yes" name="subscribe" value="yes">
  <label for="yes">Yes</label>
  <input type="radio" id="no" name="subscribe" value="no">
  <label for="no">No</label>
  
  <!-- Checkbox -->
  <input type="checkbox" id="terms" name="terms" required>
  <label for="terms">I agree to terms</label>
  
  <!-- Textarea -->
  <textarea name="message" rows="4" cols="50" maxlength="500"></textarea>
  
  <!-- Submit button -->
  <button type="submit">Submit Form</button>
</form>Forms collect user input through various input types. Text inputs, email fields, passwords, numbers, dates, and file uploads each have specific input types. Dropdown menus use <select> with <option> children. Radio buttons allow single selections from groups. Checkboxes enable multiple selections. Text areas accept multi-line input. The <form> element wraps inputs and defines submission behavior. Attributes like required, min, max, and pattern provide built-in validation.
Modern Input Types (HTML5)
<!-- Color picker -->
<input type="color" name="favcolor" value="#ff0000">
<!-- Range slider -->
<input type="range" name="volume" min="0" max="100" value="50">
<!-- Search box -->
<input type="search" name="search" placeholder="Search...">
<!-- Telephone -->
<input type="tel" name="phone" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}">
<!-- URL -->
<input type="url" name="website" placeholder="https://example.com">
<!-- Time -->
<input type="time" name="appointment">
<!-- Week picker -->
<input type="week" name="week">
<!-- Datalist (autocomplete) -->
<input list="browsers" name="browser">
<datalist id="browsers">
  <option value="Chrome">
  <option value="Firefox">
  <option value="Safari">
  <option value="Edge">
</datalist>HTML5 introduced specialized input types for better user experiences. Color pickers, range sliders, search boxes, telephone inputs, URL fields, and time pickers provide optimized interfaces. Mobile browsers display appropriate keyboards for each type. Datalists enable autocomplete functionality by suggesting values as users type. Browsers provide built-in validation for these specialized types.
Best Practices for Modern HTML
1. Semantic HTML First
<!-- Bad -->
<div class="header">
  <div class="nav">...</div>
</div>
<!-- Good -->
<header>
  <nav>...</nav>
</header>Semantic tags convey meaning while generic divs do not. Using <header> and <nav> instead of <div class="header"> and <div class="nav"> makes HTML more meaningful. Semantic markup improves accessibility for screen readers, helps search engines understand content structure, and makes code easier to read and maintain.
2. Accessibility (a11y)
<!-- Always include alt text -->
<img src="logo.png" alt="Company Logo">
<!-- Use ARIA labels when needed -->
<button aria-label="Close dialog">×</button>
<!-- Proper form labels -->
<label for="email">Email:</label>
<input type="email" id="email" name="email">
<!-- Skip navigation link -->
<a href="#main" class="skip-link">Skip to main content</a>Accessible websites work for all users including those with disabilities. Images require alt attributes so screen readers can describe them. Icon buttons need ARIA labels to convey their purpose. Form inputs must be connected to labels using matching for and id attributes. Skip links help keyboard users jump directly to main content without tabbing through navigation.
3. Performance Optimization
<!-- Lazy load images below the fold -->
<img src="image.jpg" loading="lazy" alt="Description">
<!-- Preload critical resources -->
<link rel="preload" href="font.woff2" as="font" crossorigin>
<!-- Async/defer JavaScript -->
<script src="script.js" defer></script>Performance techniques improve page loading speed and user experience. The loading="lazy" attribute defers loading offscreen images until needed. The rel="preload" attribute loads critical resources early. The defer attribute on script tags loads JavaScript without blocking page rendering. Faster pages rank higher in search engines and reduce bounce rates.
4. SEO Optimization
<!-- Descriptive title tags -->
<title>Product Name - Category - Site Name</title>
<!-- Meta descriptions -->
<meta name="description" content="Concise description under 160 characters">
<!-- Structured data (Schema.org) -->
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "Product",
  "name": "Product Name",
  "description": "Product description"
}
</script>Search engines use metadata to understand and display content. Descriptive title tags appear in search results and browser tabs. Meta descriptions under 160 characters show in search snippets. Structured data using Schema.org JSON-LD format enables rich results with ratings, prices, or other enhanced information. These optimizations improve visibility and click-through rates.
5. Mobile-First Design
<!-- Viewport meta tag -->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- Touch-friendly tap targets -->
<button style="min-height: 44px; min-width: 44px;">Tap Me</button>The viewport meta tag is essential for responsive websites. It tells mobile browsers to use device width instead of desktop width. Touch-friendly interfaces require tap targets at least 44x44 pixels for easy finger interaction. Mobile-first design ensures websites function properly on smartphones and tablets where most web traffic originates.
6. Progressive Enhancement
<!-- Provide fallbacks -->
<video controls>
  <source src="video.mp4" type="video/mp4">
  <p>Your browser doesn't support video. 
     <a href="video.mp4">Download the video</a>.</p>
</video>Progressive enhancement builds websites that work for everyone then adds features for modern browsers. Providing fallback content ensures users with older browsers or disabilities can still access information. Video elements should include download links for browsers without HTML5 support. Core functionality should never depend on cutting-edge features.
HTML Validation and Testing
Validation Tools
- W3C Validator: validator.w3.org 
- HTML5 Validator: Browser developer tools 
- Accessibility: WAVE, axe DevTools 
Common Validation Errors
<!-- Invalid: Nested anchor tags -->
<a href="#"><a href="#">Nested link</a></a>
<!-- Invalid: Block element inside inline -->
<span><div>Content</div></span>
<!-- Invalid: Duplicate IDs -->
<div id="unique"></div>
<div id="unique"></div>
<!-- Valid alternatives -->
<a href="#">Single link</a>
<div><span>Content</span></div>
<div id="unique1"></div>
<div id="unique2"></div>Valid HTML follows specific nesting rules. Anchor tags cannot be nested inside each other. Block elements cannot be placed inside inline elements. ID attributes must be unique across the entire page. Following these rules ensures consistent rendering across browsers and prevents accessibility issues. Validators can automatically detect these common mistakes.
Integration with Modern Frameworks
When working with Vue.js (which you'll study later), HTML becomes templated:
<!-- Vue.js template example -->
<div id="app">
  <h1>{{ title }}</h1>
  <ul>
    <li v-for="item in items" :key="item.id">
      {{ item.name }}
    </li>
  </ul>
  <button @click="handleClick">Click Me</button>
</div>JavaScript frameworks transform HTML into dynamic templates. Double curly braces display JavaScript variables and expressions. The v-for directive loops through arrays to create repeated elements. The :key attribute helps frameworks track elements efficiently. Event listeners like @click connect user actions to JavaScript functions. This templating approach enables reactive interfaces that update automatically when data changes.
This foundation in semantic HTML will be essential when you build dynamic applications with Express, Firebase, and Vue.js, as these frameworks ultimately generate and manipulate HTML in the browser.
Summary
HTML provides the structural foundation of web applications. While frameworks like Vue.js abstract much of the HTML writing, understanding these fundamentals is crucial for:
- Debugging rendered output 
- Optimizing performance 
- Ensuring accessibility 
- Improving SEO 
- Creating maintainable applications 
Remember: Good HTML is semantic, accessible, and performant - principles that apply whether you're writing HTML directly or through a framework.
Last updated
Was this helpful?