Introduction to Document Structure
The structure of HTML and CSS documents is fundamental to creating well-organized, maintainable, and semantically meaningful web pages. Understanding how to properly structure your HTML markup and organize your CSS code is essential for professional web development.
Key Concepts
- HTML Document Structure: The skeleton that defines the parts of a web page
- CSS Organization: How to structure and organize style rules
- Semantic Markup: Using HTML elements for their intended meaning
- Separation of Concerns: Content (HTML) separate from presentation (CSS)
- Document Flow: How elements are arranged on the page by default
1. HTML Document Structure
Basic HTML Document
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document Structure Example</title> <meta name="description" content="A comprehensive example of HTML document structure"> <meta name="keywords" content="HTML, CSS, structure, tutorial"> <meta name="author" content="Your Name"> <!-- Favicon --> <link rel="icon" type="image/x-icon" href="/favicon.ico"> <link rel="apple-touch-icon" href="/apple-touch-icon.png"> <!-- CSS Links --> <link rel="stylesheet" href="/css/reset.css"> <link rel="stylesheet" href="/css/main.css"> <!-- Preconnect to external domains --> <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <!-- External Fonts --> <link href="https://fonts.googleapis.com/css2?family=Open+Sans:wght@400;600;700&display=swap" rel="stylesheet"> <!-- Canonical URL --> <link rel="canonical" href="https://example.com/page-url"> <!-- Open Graph tags (for social media) --> <meta property="og:title" content="Document Structure Example"> <meta property="og:description" content="A comprehensive example of HTML document structure"> <meta property="og:image" content="https://example.com/image.jpg"> <meta property="og:url" content="https://example.com/page-url"> <meta property="og:type" content="website"> <!-- Twitter Card tags --> <meta name="twitter:card" content="summary_large_image"> <meta name="twitter:title" content="Document Structure Example"> <meta name="twitter:description" content="A comprehensive example of HTML document structure"> <meta name="twitter:image" content="https://example.com/image.jpg"> <!-- Robots meta tag --> <meta name="robots" content="index, follow"> <!-- Theme color for mobile browsers --> <meta name="theme-color" content="#007bff"> <!-- Base URL for relative links --> <base href="https://example.com/"> </head> <body> <!-- Page content goes here --> </body> </html>
DOCTYPE Declaration
<!-- HTML5 DOCTYPE (recommended) --> <!DOCTYPE html> <!-- Older DOCTYPEs (for legacy documents) --> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
The <html> Element
<!-- Basic html element --> <html lang="en"> <!-- With additional attributes --> <html lang="en" dir="ltr" data-theme="light"> <!-- For multilingual sites --> <html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml"> <!-- With manifest (deprecated) --> <html manifest="appcache.manifest">
The <head> Section
<head>
<!-- Character encoding (must be within first 1024 bytes) -->
<meta charset="UTF-8">
<!-- Viewport settings for responsive design -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0">
<!-- Page title (required) -->
<title>Page Title - Site Name</title>
<!-- Meta descriptions -->
<meta name="description" content="A brief description of the page content (150-160 characters)">
<meta name="keywords" content="HTML, CSS, JavaScript, tutorial">
<meta name="author" content="Author Name">
<!-- HTTP-equiv equivalents (deprecated but still used) -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="Content-Language" content="en">
<meta http-equiv="Cache-Control" content="no-cache">
<meta http-equiv="Refresh" content="30;url=https://example.com/new-page">
<!-- CSS Links -->
<link rel="stylesheet" href="/css/styles.css" media="all">
<link rel="stylesheet" href="/css/print.css" media="print">
<link rel="stylesheet" href="/css/mobile.css" media="screen and (max-width: 768px)">
<!-- JavaScript (with defer/async) -->
<script src="/js/main.js" defer></script>
<script src="https://cdn.example.com/library.js" async></script>
<!-- Preload critical resources -->
<link rel="preload" href="/fonts/custom-font.woff2" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="/css/critical.css" as="style">
<link rel="preload" href="/js/critical.js" as="script">
<!-- Prefetch for future navigation -->
<link rel="prefetch" href="/next-page.html">
<link rel="prefetch" href="/images/large-image.jpg">
<!-- DNS Prefetch -->
<link rel="dns-prefetch" href="https://api.example.com">
<link rel="dns-prefetch" href="https://images.example.com">
<!-- Preconnect -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<!-- Alternate versions -->
<link rel="alternate" href="https://example.com/en" hreflang="en">
<link rel="alternate" href="https://example.com/es" hreflang="es">
<link rel="alternate" type="application/rss+xml" title="RSS Feed" href="/feed.xml">
<!-- Canonical URL (prevents duplicate content issues) -->
<link rel="canonical" href="https://example.com/canonical-url">
<!-- Prev/Next for pagination -->
<link rel="prev" href="https://example.com/page-1">
<link rel="next" href="https://example.com/page-3">
<!-- Icons -->
<link rel="icon" href="/favicon.ico" sizes="any">
<link rel="icon" href="/icon.svg" type="image/svg+xml">
<link rel="apple-touch-icon" href="/apple-touch-icon.png">
<link rel="manifest" href="/site.webmanifest">
<!-- Open Graph (Facebook, LinkedIn) -->
<meta property="og:title" content="Page Title">
<meta property="og:type" content="website">
<meta property="og:url" content="https://example.com/page">
<meta property="og:image" content="https://example.com/image.jpg">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:description" content="Page description">
<meta property="og:site_name" content="Site Name">
<meta property="og:locale" content="en_US">
<!-- Twitter Card -->
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:site" content="@username">
<meta name="twitter:creator" content="@author">
<meta name="twitter:title" content="Page Title">
<meta name="twitter:description" content="Page description">
<meta name="twitter:image" content="https://example.com/image.jpg">
<!-- Pinterest -->
<meta name="pinterest" content="nopin" description="Don't save this content">
<!-- Theme color (mobile browsers) -->
<meta name="theme-color" content="#007bff" media="(prefers-color-scheme: light)">
<meta name="theme-color" content="#1a1a1a" media="(prefers-color-scheme: dark)">
<!-- Robots -->
<meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1, max-video-preview:-1">
<meta name="googlebot" content="index, follow">
<!-- Verification (Google Search Console, etc.) -->
<meta name="google-site-verification" content="verification-code">
<meta name="msvalidate.01" content="bing-verification-code">
<meta name="yandex-verification" content="yandex-verification-code">
<!-- Script with JSON-LD structured data -->
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "WebPage",
"name": "Page Title",
"description": "Page description",
"author": {
"@type": "Person",
"name": "Author Name"
},
"datePublished": "2024-03-12",
"dateModified": "2024-03-12"
}
</script>
</head>
The <body> Section
<body> <!-- Page header --> <header> <h1>Site Title</h1> <nav> <ul> <li><a href="/">Home</a></li> <li><a href="/about">About</a></li> <li><a href="/contact">Contact</a></li> </ul> </nav> </header> <!-- Main content --> <main> <article> <header> <h2>Article Title</h2> <p>Published on <time datetime="2024-03-12">March 12, 2024</time></p> </header> <section> <h3>Section Title</h3> <p>Section content...</p> </section> <section> <h3>Another Section</h3> <p>More content...</p> </section> <footer> <p>Article footer</p> </footer> </article> <aside> <h3>Related Content</h3> <ul> <li><a href="#">Related article 1</a></li> <li><a href="#">Related article 2</a></li> </ul> </aside> </main> <!-- Page footer --> <footer> <p>© 2024 Site Name. All rights reserved.</p> <address> Contact: <a href="mailto:[email protected]">[email protected]</a> </address> </footer> <!-- Scripts at end of body for performance --> <script src="/js/main.js"></script> </body>
2. Semantic HTML Structure
Document Outline with Headings
<body> <!-- Proper heading hierarchy --> <h1>Main Page Title (only one per page)</h1> <section> <h2>Section Level 2</h2> <p>Content...</p> <section> <h3>Subsection Level 3</h3> <p>More content...</p> <h4>Level 4 if needed</h4> <p>Even more specific content...</p> </section> <section> <h3>Another Subsection</h3> <p>Different content...</p> </section> </section> <section> <h2>Another Main Section</h2> <p>More content...</p> </section> </body>
Article Structure
<article> <!-- Article header --> <header> <h1>Article Title</h1> <div class="byline"> <address class="author"> <a rel="author" href="/authors/john-doe">John Doe</a> </address> <time datetime="2024-03-12T14:30" pubdate>March 12, 2024</time> </div> </header> <!-- Article content --> <div class="content"> <p>Introduction paragraph...</p> <h2>First Section</h2> <p>Section content...</p> <figure> <img src="image.jpg" alt="Description"> <figcaption>Image caption</figcaption> </figure> <h2>Second Section</h2> <p>More content...</p> <blockquote cite="https://example.com/source"> <p>Notable quote from the article...</p> </blockquote> <h3>Subsection</h3> <p>Detailed content...</p> <ul> <li>List item 1</li> <li>List item 2</li> <li>List item 3</li> </ul> </div> <!-- Article footer with metadata --> <footer> <p>Categories: <a href="/category/tech">Tech</a>, <a href="/category/web">Web</a></p> <p>Tags: <a href="/tag/html">HTML</a>, <a href="/tag/css">CSS</a></p> <p>Share: <a href="https://twitter.com/share?url=...">Twitter</a> <a href="https://facebook.com/sharer.php?u=...">Facebook</a> </p> </footer> </article>
Navigation Structures
<!-- Main navigation --> <nav aria-label="Main navigation"> <ul> <li><a href="/" aria-current="page">Home</a></li> <li><a href="/products">Products</a> <ul> <li><a href="/products/electronics">Electronics</a></li> <li><a href="/products/clothing">Clothing</a></li> <li><a href="/products/books">Books</a></li> </ul> </li> <li><a href="/services">Services</a></li> <li><a href="/about">About</a></li> <li><a href="/contact">Contact</a></li> </ul> </nav> <!-- Breadcrumb navigation --> <nav aria-label="Breadcrumb"> <ol class="breadcrumb"> <li><a href="/">Home</a></li> <li><a href="/products">Products</a></li> <li><a href="/products/electronics">Electronics</a></li> <li aria-current="page">Smartphones</li> </ol> </nav> <!-- Pagination --> <nav aria-label="Pagination"> <ul class="pagination"> <li><a href="?page=1" aria-label="Previous page" rel="prev">«</a></li> <li><a href="?page=1" aria-label="Page 1">1</a></li> <li><span aria-current="page">2</span></li> <li><a href="?page=3" aria-label="Page 3">3</a></li> <li><a href="?page=4" aria-label="Page 4">4</a></li> <li><a href="?page=3" aria-label="Next page" rel="next">»</a></li> </ul> </nav>
3. CSS Document Structure
CSS File Organization
/* ========================================
RESET / NORMALIZE
======================================== */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* ========================================
VARIABLES / CUSTOM PROPERTIES
======================================== */
:root {
/* Colors */
--color-primary: #007bff;
--color-secondary: #6c757d;
--color-success: #28a745;
--color-danger: #dc3545;
--color-warning: #ffc107;
--color-info: #17a2b8;
--color-light: #f8f9fa;
--color-dark: #343a40;
--color-white: #ffffff;
--color-black: #000000;
/* Typography */
--font-family-sans: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
--font-family-serif: Georgia, 'Times New Roman', Times, serif;
--font-family-mono: 'Courier New', Courier, monospace;
--font-size-base: 16px;
--font-size-sm: 0.875rem;
--font-size-lg: 1.125rem;
--font-weight-normal: 400;
--font-weight-bold: 700;
--line-height-base: 1.5;
/* Spacing */
--spacing-xs: 0.25rem;
--spacing-sm: 0.5rem;
--spacing-md: 1rem;
--spacing-lg: 1.5rem;
--spacing-xl: 2rem;
--spacing-xxl: 3rem;
/* Border radius */
--border-radius-sm: 0.25rem;
--border-radius-md: 0.5rem;
--border-radius-lg: 1rem;
--border-radius-circle: 50%;
/* Shadows */
--shadow-sm: 0 1px 3px rgba(0,0,0,0.12), 0 1px 2px rgba(0,0,0,0.24);
--shadow-md: 0 4px 6px rgba(0,0,0,0.1);
--shadow-lg: 0 10px 15px rgba(0,0,0,0.1);
--shadow-xl: 0 20px 25px rgba(0,0,0,0.1);
/* Transitions */
--transition-fast: 150ms ease;
--transition-normal: 300ms ease;
--transition-slow: 500ms ease;
/* Z-index */
--z-index-dropdown: 1000;
--z-index-sticky: 1020;
--z-index-fixed: 1030;
--z-index-modal-backdrop: 1040;
--z-index-modal: 1050;
--z-index-popover: 1060;
--z-index-tooltip: 1070;
/* Container widths */
--container-sm: 540px;
--container-md: 720px;
--container-lg: 960px;
--container-xl: 1140px;
--container-xxl: 1320px;
}
/* Dark theme variables */
@media (prefers-color-scheme: dark) {
:root {
--color-primary: #375a7f;
--color-light: #2d2d2d;
--color-dark: #f8f9fa;
--color-white: #1a1a1a;
--color-black: #ffffff;
}
}
/* ========================================
BASE STYLES
======================================== */
html {
font-size: var(--font-size-base);
scroll-behavior: smooth;
}
body {
font-family: var(--font-family-sans);
font-size: var(--font-size-base);
font-weight: var(--font-weight-normal);
line-height: var(--line-height-base);
color: var(--color-dark);
background-color: var(--color-white);
min-height: 100vh;
text-rendering: optimizeSpeed;
}
/* ========================================
TYPOGRAPHY
======================================== */
h1, h2, h3, h4, h5, h6 {
margin-top: 0;
margin-bottom: var(--spacing-md);
font-weight: var(--font-weight-bold);
line-height: 1.2;
}
h1 { font-size: 2.5rem; }
h2 { font-size: 2rem; }
h3 { font-size: 1.75rem; }
h4 { font-size: 1.5rem; }
h5 { font-size: 1.25rem; }
h6 { font-size: 1rem; }
p {
margin-top: 0;
margin-bottom: var(--spacing-md);
}
a {
color: var(--color-primary);
text-decoration: none;
transition: color var(--transition-fast);
}
a:hover {
color: var(--color-primary-dark);
text-decoration: underline;
}
/* ========================================
LAYOUT
======================================== */
.container {
width: 100%;
padding-right: var(--spacing-md);
padding-left: var(--spacing-md);
margin-right: auto;
margin-left: auto;
}
@media (min-width: 576px) {
.container { max-width: var(--container-sm); }
}
@media (min-width: 768px) {
.container { max-width: var(--container-md); }
}
@media (min-width: 992px) {
.container { max-width: var(--container-lg); }
}
@media (min-width: 1200px) {
.container { max-width: var(--container-xl); }
}
@media (min-width: 1400px) {
.container { max-width: var(--container-xxl); }
}
/* ========================================
COMPONENTS
======================================== */
/* Buttons */
.btn {
display: inline-block;
padding: var(--spacing-sm) var(--spacing-lg);
font-size: 1rem;
font-weight: var(--font-weight-normal);
line-height: 1.5;
text-align: center;
text-decoration: none;
vertical-align: middle;
cursor: pointer;
border: 1px solid transparent;
border-radius: var(--border-radius-sm);
transition: all var(--transition-fast);
}
.btn-primary {
color: var(--color-white);
background-color: var(--color-primary);
border-color: var(--color-primary);
}
.btn-primary:hover {
color: var(--color-white);
background-color: var(--color-primary-dark);
border-color: var(--color-primary-dark);
}
/* Cards */
.card {
position: relative;
display: flex;
flex-direction: column;
min-width: 0;
word-wrap: break-word;
background-color: var(--color-white);
background-clip: border-box;
border: 1px solid rgba(0,0,0,0.125);
border-radius: var(--border-radius-md);
box-shadow: var(--shadow-sm);
transition: box-shadow var(--transition-normal);
}
.card:hover {
box-shadow: var(--shadow-lg);
}
.card-body {
flex: 1 1 auto;
padding: var(--spacing-lg);
}
.card-title {
margin-bottom: var(--spacing-sm);
font-size: 1.25rem;
font-weight: var(--font-weight-bold);
}
.card-text {
margin-bottom: var(--spacing-md);
}
/* ========================================
UTILITIES
======================================== */
/* Spacing utilities */
.m-0 { margin: 0; }
.mt-1 { margin-top: var(--spacing-xs); }
.mt-2 { margin-top: var(--spacing-sm); }
.mt-3 { margin-top: var(--spacing-md); }
.mt-4 { margin-top: var(--spacing-lg); }
.mt-5 { margin-top: var(--spacing-xl); }
.mb-1 { margin-bottom: var(--spacing-xs); }
.mb-2 { margin-bottom: var(--spacing-sm); }
.mb-3 { margin-bottom: var(--spacing-md); }
.mb-4 { margin-bottom: var(--spacing-lg); }
.mb-5 { margin-bottom: var(--spacing-xl); }
.p-0 { padding: 0; }
.p-1 { padding: var(--spacing-xs); }
.p-2 { padding: var(--spacing-sm); }
.p-3 { padding: var(--spacing-md); }
.p-4 { padding: var(--spacing-lg); }
.p-5 { padding: var(--spacing-xl); }
/* Text utilities */
.text-center { text-align: center; }
.text-left { text-align: left; }
.text-right { text-align: right; }
.text-justify { text-align: justify; }
.text-primary { color: var(--color-primary); }
.text-success { color: var(--color-success); }
.text-danger { color: var(--color-danger); }
.text-warning { color: var(--color-warning); }
/* Display utilities */
.d-none { display: none; }
.d-block { display: block; }
.d-inline { display: inline; }
.d-inline-block { display: inline-block; }
.d-flex { display: flex; }
.d-grid { display: grid; }
/* Flex utilities */
.flex-row { flex-direction: row; }
.flex-column { flex-direction: column; }
.justify-content-center { justify-content: center; }
.justify-content-between { justify-content: space-between; }
.align-items-center { align-items: center; }
/* Responsive utilities */
@media (min-width: 768px) {
.d-md-none { display: none; }
.d-md-block { display: block; }
.text-md-center { text-align: center; }
}
/* ========================================
ANIMATIONS
======================================== */
@keyframes fadeIn {
from {
opacity: 0;
}
to {
opacity: 1;
}
}
@keyframes slideInUp {
from {
transform: translateY(30px);
opacity: 0;
}
to {
transform: translateY(0);
opacity: 1;
}
}
.animate-fade-in {
animation: fadeIn var(--transition-normal);
}
.animate-slide-up {
animation: slideInUp var(--transition-normal);
}
/* ========================================
PRINT STYLES
======================================== */
@media print {
body {
font-size: 12pt;
line-height: 1.5;
color: #000;
background: #fff;
}
.no-print {
display: none !important;
}
a[href]::after {
content: " (" attr(href) ")";
}
a[href^="#"]::after {
content: "";
}
}
4. CSS Organization Methodologies
BEM (Block Element Modifier)
/* BEM Naming Convention */
/* Block: standalone component */
.card { }
/* Element: part of a block (double underscore) */
.card__title { }
.card__image { }
.card__content { }
/* Modifier: variation of block/element (double dash) */
.card--featured { }
.card__title--large { }
/* Example */
.nav {
background: #333;
}
.nav__list {
display: flex;
list-style: none;
}
.nav__item {
margin-right: 1rem;
}
.nav__link {
color: white;
text-decoration: none;
}
.nav__link--active {
font-weight: bold;
border-bottom: 2px solid white;
}
.nav__link:hover {
text-decoration: underline;
}
SMACSS (Scalable and Modular Architecture for CSS)
/* ========================================
SMACSS Categories
======================================== */
/* Base Styles */
body {
margin: 0;
font-family: sans-serif;
}
h1, h2, h3 {
margin: 0 0 1rem 0;
}
a {
color: blue;
}
/* Layout Styles */
.l-header {
position: fixed;
top: 0;
width: 100%;
}
.l-main {
max-width: 1200px;
margin: 0 auto;
padding: 2rem;
}
.l-footer {
margin-top: 2rem;
padding: 1rem;
background: #f5f5f5;
}
/* Module Styles */
.module-card {
border: 1px solid #ddd;
border-radius: 4px;
}
.module-card-header {
padding: 1rem;
background: #f5f5f5;
}
.module-card-body {
padding: 1rem;
}
/* State Styles */
.is-hidden {
display: none;
}
.is-expanded {
display: block;
}
.is-active {
font-weight: bold;
}
/* Theme Styles */
.theme-dark {
background: #333;
color: white;
}
.theme-dark a {
color: #8bbfff;
}
Atomic CSS
/* Atomic CSS (functional) */
/* Single-purpose classes */
.m-0 { margin: 0; }
.m-4 { margin: 1rem; }
.p-0 { padding: 0; }
.p-4 { padding: 1rem; }
.text-center { text-align: center; }
.text-left { text-align: left; }
.text-right { text-align: right; }
.bg-blue { background-color: blue; }
.bg-red { background-color: red; }
.bg-green { background-color: green; }
.flex { display: flex; }
.grid { display: grid; }
.block { display: block; }
.hidden { display: none; }
.w-full { width: 100%; }
.h-full { height: 100%; }
/* Example usage */
<div class="flex justify-center items-center p-4 bg-blue text-white">
<h1 class="text-center">Centered Content</h1>
</div>
5. CSS Architecture Patterns
ITCSS (Inverted Triangle CSS)
/* ========================================
ITCSS Layers (from generic to specific)
======================================== */
/* 1. Settings - Variables, config */
:root {
--color-primary: #007bff;
--spacing-unit: 8px;
}
/* 2. Tools - Mixins, functions */
@mixin center {
display: flex;
align-items: center;
justify-content: center;
}
/* 3. Generic - Reset, normalize */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* 4. Elements - Bare element styles */
body {
font-family: sans-serif;
line-height: 1.5;
}
h1 {
font-size: 2rem;
margin-bottom: 1rem;
}
a {
color: var(--color-primary);
}
/* 5. Objects - Layout patterns */
.o-container {
max-width: 1200px;
margin: 0 auto;
padding: 0 1rem;
}
.o-grid {
display: grid;
gap: 2rem;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
}
/* 6. Components - UI components */
.c-card {
border: 1px solid #ddd;
border-radius: 4px;
overflow: hidden;
}
.c-card__image {
width: 100%;
height: 200px;
object-fit: cover;
}
.c-card__content {
padding: 1rem;
}
.c-card__title {
font-size: 1.25rem;
margin-bottom: 0.5rem;
}
/* 7. Utilities - Helpers, overrides */
.u-text-center {
text-align: center;
}
.u-mt-2 {
margin-top: 2rem;
}
.u-hidden {
display: none;
}
OOCSS (Object Oriented CSS)
/* OOCSS - Separate structure from skin */
/* Structure */
.media {
display: flex;
align-items: flex-start;
gap: 1rem;
}
.media__figure {
flex-shrink: 0;
}
.media__body {
flex: 1;
}
/* Skin */
.media--bordered {
border: 1px solid #ddd;
padding: 1rem;
border-radius: 4px;
}
.media--highlighted {
background-color: #f9f9f9;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.media__figure--rounded {
border-radius: 50%;
overflow: hidden;
}
/* Button object */
.btn {
display: inline-block;
padding: 0.5rem 1rem;
border: none;
cursor: pointer;
font-size: 1rem;
text-align: center;
text-decoration: none;
}
.btn--primary {
background-color: blue;
color: white;
}
.btn--secondary {
background-color: gray;
color: white;
}
.btn--large {
padding: 1rem 2rem;
font-size: 1.25rem;
}
6. Responsive Document Structure
Viewport Meta Tag
<!-- Basic viewport settings --> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- With additional options --> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, minimum-scale=1.0, user-scalable=yes"> <!-- For fixed-width designs (not recommended) --> <meta name="viewport" content="width=1024"> <!-- For iOS specific --> <meta name="viewport" content="width=device-width, initial-scale=1.0, viewport-fit=cover">
Media Queries Structure
/* Mobile First Approach */
/* Base styles (mobile) */
.container {
width: 100%;
padding: 1rem;
}
.grid {
display: grid;
gap: 1rem;
grid-template-columns: 1fr;
}
/* Tablet (>= 768px) */
@media (min-width: 768px) {
.container {
max-width: 720px;
margin: 0 auto;
}
.grid {
grid-template-columns: repeat(2, 1fr);
}
.sidebar {
display: block;
}
}
/* Desktop (>= 1024px) */
@media (min-width: 1024px) {
.container {
max-width: 960px;
}
.grid {
grid-template-columns: repeat(3, 1fr);
}
.header {
position: sticky;
top: 0;
}
}
/* Large Desktop (>= 1200px) */
@media (min-width: 1200px) {
.container {
max-width: 1140px;
}
}
/* Print styles */
@media print {
.header,
.footer,
.sidebar {
display: none;
}
body {
font-size: 12pt;
line-height: 1.5;
}
}
/* Orientation specific */
@media (orientation: landscape) {
.hero {
height: 80vh;
}
}
@media (orientation: portrait) {
.hero {
height: 60vh;
}
}
/* Feature queries */
@supports (display: grid) {
.grid {
display: grid;
}
}
@supports not (display: grid) {
.grid {
display: flex;
flex-wrap: wrap;
}
}
Responsive Images
<!-- Responsive images with srcset --> <img src="image-small.jpg" srcset="image-small.jpg 300w, image-medium.jpg 600w, image-large.jpg 900w" sizes="(max-width: 300px) 300px, (max-width: 600px) 600px, 900px" alt="Responsive image" > <!-- Picture element for art direction --> <picture> <source media="(max-width: 768px)" srcset="image-mobile.jpg"> <source media="(max-width: 1024px)" srcset="image-tablet.jpg"> <img src="image-desktop.jpg" alt="Art-directed image"> </picture> <!-- WebP format with fallback --> <picture> <source type="image/webp" srcset="image.webp"> <img src="image.jpg" alt="Image with WebP support"> </picture>
7. CSS Import and Organization
CSS @import Rules
/* main.css - Main stylesheet */
/* Import order matters */
@import url('reset.css');
@import url('variables.css');
@import url('typography.css');
@import url('layout.css');
@import 'components/buttons.css';
@import 'components/cards.css';
@import 'pages/home.css' screen and (min-width: 768px);
@import 'print.css' print;
/* Media-specific imports */
@import 'mobile.css' screen and (max-width: 767px);
@import 'desktop.css' screen and (min-width: 1024px);
/* Conditional import based on feature */
@import 'grid.css' supports(display: grid);
Multiple Stylesheets Structure
<!-- HTML linking multiple CSS files -->
<!DOCTYPE html>
<html lang="en">
<head>
<!-- Critical CSS (inline for performance) -->
<style>
/* Critical above-the-fold styles */
.header { background: #333; color: white; }
.hero { min-height: 50vh; }
</style>
<!-- Non-critical CSS (loaded asynchronously) -->
<link rel="preload" href="css/main.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="css/main.css"></noscript>
<!-- Media-specific stylesheets -->
<link rel="stylesheet" href="css/print.css" media="print">
<link rel="stylesheet" href="css/mobile.css" media="screen and (max-width: 767px)">
<link rel="stylesheet" href="css/desktop.css" media="screen and (min-width: 1024px)">
</head>
CSS File Structure Example
css/ ├── base/ │ ├── _reset.css │ ├── _variables.css │ ├── _typography.css │ └── _animations.css ├── components/ │ ├── _buttons.css │ ├── _cards.css │ ├── _forms.css │ ├── _modals.css │ └── _navigation.css ├── layout/ │ ├── _header.css │ ├── _footer.css │ ├── _sidebar.css │ └── _grid.css ├── pages/ │ ├── _home.css │ ├── _about.css │ └── _contact.css ├── themes/ │ ├── _light.css │ └── _dark.css ├── utils/ │ ├── _mixins.css │ ├── _functions.css │ └── _helpers.css └── main.css
8. HTML5 Document Outline
Document Outline Algorithm
<!DOCTYPE html> <html lang="en"> <head> <title>Document Outline Example</title> </head> <body> <!-- Sectioning content creates implicit outline --> <h1>Main Title</h1> <section> <h2>Section 1</h2> <p>Content...</p> <section> <h3>Subsection 1.1</h3> <p>Content...</p> </section> <section> <h3>Subsection 1.2</h3> <p>Content...</p> </section> </section> <article> <h2>Article Title</h2> <p>Content...</p> <section> <h3>Article Section</h3> <p>Content...</p> </section> </article> <aside> <h2>Related Content</h2> <p>Content...</p> </aside> <nav> <h2>Navigation</h2> <ul> <li><a href="#">Link</a></li> </ul> </nav> </body> </html>
Sectioning Elements
<!-- Sectioning elements create new sections in the document outline --> <body> <header> <h1>Site Title</h1> <nav>...</nav> </header> <main> <article> <header> <h2>Article Title</h2> </header> <section> <h3>Section Title</h3> <p>Content...</p> </section> <footer> <p>Article footer</p> </footer> </article> <aside> <h3>Sidebar</h3> <p>Related content...</p> </aside> </main> <footer> <p>Site footer</p> </footer> </body>
9. Accessibility in Document Structure
ARIA Landmarks
<body> <!-- ARIA landmarks for screen readers --> <header role="banner"> <h1>Site Title</h1> </header> <nav role="navigation" aria-label="Main menu"> <ul> <li><a href="/">Home</a></li> </ul> </nav> <main role="main"> <article role="article"> <h2>Article Title</h2> <p>Content...</p> </article> <aside role="complementary"> <h3>Related</h3> </aside> </main> <section role="region" aria-label="Newsletter signup"> <h2>Subscribe</h2> <form>...</form> </section> <footer role="contentinfo"> <p>Copyright 2024</p> </footer> <!-- Search landmark --> <div role="search"> <input type="search" placeholder="Search..."> </div> <!-- Form landmark --> <form role="form" aria-label="Contact form"> <!-- form fields --> </form> </body>
Skip Links
<body>
<!-- Skip link for keyboard users -->
<a href="#main-content" class="skip-link">Skip to main content</a>
<header>
<nav>
<!-- complex navigation -->
</nav>
</header>
<main id="main-content" tabindex="-1">
<!-- main content -->
</main>
<style>
.skip-link {
position: absolute;
top: -40px;
left: 0;
background: #000;
color: white;
padding: 8px;
z-index: 100;
text-decoration: none;
}
.skip-link:focus {
top: 0;
}
</style>
</body>
10. Performance Optimization
Critical CSS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Optimized Page</title>
<!-- Critical CSS (inline) -->
<style>
/* Critical above-the-fold styles */
body {
margin: 0;
font-family: sans-serif;
}
header {
background: #333;
color: white;
padding: 1rem;
}
.hero {
min-height: 50vh;
display: flex;
align-items: center;
justify-content: center;
background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
color: white;
}
</style>
<!-- Preload non-critical CSS -->
<link rel="preload" href="css/main.css" as="style" onload="this.onload=null;this.rel='stylesheet'">
<noscript><link rel="stylesheet" href="css/main.css"></noscript>
<!-- Load non-critical CSS asynchronously -->
<script>
/*! loadCSS rel=preload polyfill. [c]2017 Filament Group, Inc. MIT License */
(function( w ){
"use strict";
if( !w.loadCSS ){
w.loadCSS = function(){};
}
var rp = loadCSS.relpreload = {};
rp.support = function(){
try {
return w.document.createElement( "link" ).relList.supports( "preload" );
} catch( e ) {
return false;
}
};
rp.poly = function(){
var links = w.document.getElementsByTagName( "link" );
for( var i = 0; i < links.length; i++ ){
var link = links[ i ];
if( link.rel === "preload" && link.getAttribute( "as" ) === "style" ){
w.addEventListener( "load", function() {
link.rel = "stylesheet";
});
break;
}
}
};
if( !rp.support() ){
rp.poly();
}
})( window );
</script>
</head>
<body>
<!-- Page content -->
<header>...</header>
<main>...</main>
<!-- Defer non-critical JavaScript -->
<script src="js/non-critical.js" defer></script>
</body>
</html>
11. Document Validation
HTML Validation
<!DOCTYPE html> <html lang="en"> <head> <!-- W3C validation hints --> <meta charset="UTF-8"> <title>Valid HTML Document</title> </head> <body> <!-- Avoid common validation errors --> <!-- Don't use deprecated elements --> <!-- <center>This is centered</center> --> <!-- Bad --> <div style="text-align: center">This is centered</div> <!-- Good --> <!-- Always include alt text on images --> <img src="image.jpg" alt="Descriptive text"> <!-- Don't use inline styles (prefer classes) --> <!-- <div style="color: red">Text</div> --> <!-- Bad --> <div class="text-red">Text</div> <!-- Good --> <!-- Close all tags properly --> <p>Paragraph content</p> <!-- Always close --> <!-- Use proper nesting --> <div> <p>Content</p> <!-- Good --> </div> <!-- <div><p>Content</div></p> --> <!-- Bad - incorrect nesting --> <!-- IDs must be unique --> <div id="unique-id">First</div> <div id="unique-id">Second</div> <!-- Bad - duplicate ID --> <!-- Use semantic elements --> <div class="header">...</div> <!-- Acceptable but better: --> <header>...</header> <!-- Good --> </body> </html>
CSS Validation
/* Avoid common CSS validation errors */
/* Use correct property names */
/* colorr: red; */ /* Bad - misspelled */
color: red; /* Good */
/* Use correct property values */
/* display: blok; */ /* Bad - misspelled */
display: block; /* Good */
/* Don't use experimental properties without prefixes */
.example {
-webkit-transition: all 0.3s;
-moz-transition: all 0.3s;
-ms-transition: all 0.3s;
-o-transition: all 0.3s;
transition: all 0.3s;
}
/* Use correct units */
/* width: 100; */ /* Bad - missing unit */
width: 100px; /* Good */
/* Don't use non-existent pseudo-classes */
/* element:non-existent { } */ /* Bad */
/* Use correct function syntax */
/* background: url(image.jpg; */ /* Bad - missing closing parenthesis */
background: url(image.jpg); /* Good */
/* Don't use browser-specific hacks */
/* .element { _color: red; } */ /* Bad - IE hack */
12. Best Practices Summary
HTML Best Practices
<!DOCTYPE html> <html lang="en"> <head> <!-- 1. Always declare doctype --> <!-- 2. Set character encoding --> <meta charset="UTF-8"> <!-- 3. Set viewport for responsive design --> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <!-- 4. Always have a title --> <title>Page Title</title> <!-- 5. Include meta description --> <meta name="description" content="Page description"> </head> <body> <!-- 6. Use semantic HTML --> <header></header> <nav></nav> <main></main> <article></article> <section></section> <aside></aside> <footer></footer> <!-- 7. Use heading hierarchy (h1-h6) --> <h1>Main Title</h1> <h2>Section Title</h2> <h3>Subsection Title</h3> <!-- 8. Always add alt text to images --> <img src="image.jpg" alt="Description"> <!-- 9. Use lists for related items --> <ul> <li>Item 1</li> <li>Item 2</li> </ul> <!-- 10. Label form inputs --> <label for="name">Name:</label> <input type="text" id="name" name="name"> <!-- 11. Use ARIA attributes when needed --> <button aria-label="Close">×</button> <!-- 12. Ensure keyboard navigation --> <a href="#main" class="skip-link">Skip to content</a> <!-- 13. Validate your HTML --> <!-- Use W3C validator: https://validator.w3.org/ --> </body> </html>
CSS Best Practices
/* 1. Use a CSS reset or normalize */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* 2. Use CSS variables for consistency */
:root {
--primary-color: #007bff;
--spacing-unit: 8px;
}
/* 3. Follow a naming convention (BEM, etc.) */
.card { }
.card__title { }
.card--featured { }
/* 4. Keep specificity low */
/* Avoid overly specific selectors */
/* div.container ul li a { } */ /* Bad */
.nav-link { } /* Good */
/* 5. Use meaningful class names */
/* .r { } */ /* Bad - cryptic */
/* .red-text { } */ /* Bad - describes appearance */
.error-message { } /* Good - describes purpose */
/* 6. Organize CSS logically */
/* Variables, Reset, Base, Layout, Components, Utilities */
/* 7. Use shorthand properties */
/* margin-top: 10px; margin-bottom: 10px; */ /* Verbose */
margin: 10px 0; /* Good */
/* 8. Avoid !important */
/* .important { color: red !important; } */ /* Bad - use only as last resort */
/* 9. Group media queries */
/* Instead of scattering media queries, group them */
@media (max-width: 768px) {
.header { ... }
.nav { ... }
.footer { ... }
}
/* 10. Comment your code */
/* ========================================
COMPONENT: Cards
======================================== */
/* 11. Use relative units */
/* width: 200px; */ /* Less flexible */
width: 20rem; /* More flexible */
/* 12. Test across browsers */
/* Use autoprefixer or manually add prefixes */
.example {
display: -webkit-box;
display: -ms-flexbox;
display: flex;
}
/* 13. Optimize performance */
/* Use will-change for animations */
.animated {
will-change: transform;
}
/* 14. Validate your CSS */
/* Use W3C CSS validator: https://jigsaw.w3.org/css-validator/ */
Conclusion
Key Takeaways
- HTML document structure consists of
<!DOCTYPE>,<html>,<head>, and<body> - Semantic HTML improves accessibility, SEO, and maintainability
- CSS organization should follow a consistent methodology (BEM, SMACSS, ITCSS)
- Responsive design requires proper viewport settings and media queries
- Performance optimization includes critical CSS, lazy loading, and efficient selectors
- Accessibility should be built into the document structure from the start
- Validation ensures code quality and cross-browser compatibility
Document Structure Checklist
- [ ]
<!DOCTYPE html>declaration present - [ ]
<html lang="en">with appropriate language - [ ]
<meta charset="UTF-8">in<head> - [ ]
<meta name="viewport">for responsive design - [ ]
<title>element with descriptive title - [ ] Semantic elements used (
<header>,<nav>,<main>, etc.) - [ ] Proper heading hierarchy (
h1-h6) - [ ] Alt text on all images
- [ ] Labels associated with form inputs
- [ ] ARIA landmarks where appropriate
- [ ] CSS organized with methodology
- [ ] Media queries for responsive design
- [ ] Valid HTML and CSS
Mastering document structure in HTML and CSS is fundamental to creating well-organized, maintainable, and accessible websites. A solid understanding of these principles will serve as the foundation for all your web development projects.
HTML & CSS Learning Guides, Exercises, Projects, Design Systems, Accessibility & Performance (Related to HTML & CSS Development)
HTML & CSS Quiz – Comprehensive Assessment:
This quiz evaluates core knowledge of HTML and CSS including structure, styling, layout, forms, and responsive design. It is used to test practical understanding of front-end fundamentals and identify skill levels in web development.
Read more: https://macronepal.com/bash/html-and-css-quiz-comprehensive-assessment/
Complete Guide to HTML & CSS Tooling & Automation:
This guide explains tools and automation workflows used in modern web development, such as preprocessors, build tools, and task runners that improve efficiency in HTML and CSS projects.
Read more: https://macronepal.com/bash/complete-guide-to-html-and-css-tooling-automation/
Complete HTML & CSS Exercises:
A collection of practical exercises designed to strengthen HTML and CSS skills through hands-on coding tasks, covering layout, styling, and responsive design concepts.
Read more: https://macronepal.com/bash/complete-html-and-css-exercises/
Complete HTML & CSS Landing Page Project:
This project focuses on building a full landing page using HTML and CSS, helping learners understand real-world website structure, layout design, and UI development.
Read more: https://macronepal.com/bash/complete-html-css-landing-page-project/
HTML & CSS Debugging and Testing Guide:
This guide teaches how to identify and fix errors in HTML and CSS code, along with testing techniques to ensure websites work correctly across browsers.
Read more: https://macronepal.com/bash/complete-guide-to-html-and-css-debugging-testing/
HTML & CSS Design Systems Guide:
A design system approach helps maintain consistency in UI development using reusable components, styles, and patterns across web projects.
Read more: https://macronepal.com/html-and-css/complete-guide-to-html-and-css-design-systems/
HTML & CSS Accessibility (A11y) Guide:
This guide focuses on making websites accessible for all users, including proper semantic HTML, keyboard navigation, alt text, and screen reader support.
Read more: https://macronepal.com/bash/complete-guide-to-html-css-accessibility-a11y/
HTML & CSS Performance Guide:
This topic explains optimization techniques such as reducing file size, improving loading speed, and writing efficient HTML and CSS for better website performance.
Read more: https://macronepal.com/bash/complete-guide-to-html-and-css-performance/
HTML & CSS Design Systems (Advanced Overview):
Design systems help developers maintain scalable and consistent UI components across large projects using structured HTML and reusable CSS patterns.
Read more: https://macronepal.com/html-and-css/complete-guide-to-html-and-css-design-systems/