Complete Guide to HTML and CSS Essentials

Introduction to HTML and CSS

HTML (HyperText Markup Language) and CSS (Cascading Style Sheets) are the foundational technologies for creating web pages. HTML provides the structure and content, while CSS handles the presentation and styling. Together, they form the backbone of every website you see on the internet.

Key Concepts

  • HTML: Defines the structure and semantics of web content
  • CSS: Controls the visual presentation and layout
  • Separation of Concerns: Content (HTML) separated from presentation (CSS)
  • Progressive Enhancement: Build solid HTML foundation, then enhance with CSS
  • Responsive Design: Adapt layouts for different screen sizes

1. HTML Basics

Document Structure

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>My First Web Page</title>
<meta name="description" content="A complete guide to HTML and CSS">
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>Welcome to My Website</h1>
<nav>
<ul>
<li><a href="#home">Home</a></li>
<li><a href="#about">About</a></li>
<li><a href="#contact">Contact</a></li>
</ul>
</nav>
</header>
<main>
<article>
<h2>Article Title</h2>
<p>This is a paragraph of text.</p>
</article>
</main>
<footer>
<p>&copy; 2024 My Website</p>
</footer>
</body>
</html>

Essential HTML Elements

Text Elements

<!-- Headings -->
<h1>Main Heading (most important)</h1>
<h2>Section Heading</h2>
<h3>Subsection Heading</h3>
<h4>Smaller Heading</h4>
<h5>Even Smaller</h5>
<h6>Least Important</h6>
<!-- Paragraphs -->
<p>This is a regular paragraph of text. It can contain multiple sentences and will wrap automatically.</p>
<!-- Text formatting -->
<strong>Bold/Important text</strong>
<em>Italic/Emphasized text</em>
<mark>Highlighted text</mark>
<small>Smaller text</small>
<del>Deleted text</del>
<ins>Inserted text</ins>
<sub>Subscript</sub>
<sup>Superscript</sup>
<!-- Line breaks and horizontal rules -->
<br>  <!-- Line break -->
<hr>  <!-- Horizontal rule -->
<!-- Quotes -->
<blockquote cite="https://example.com">
This is a long blockquote that might span multiple lines.
</blockquote>
<q>Short inline quote</q>
<!-- Abbreviations -->
<abbr title="HyperText Markup Language">HTML</abbr>
<!-- Address -->
<address>
Written by John Doe<br>
Visit us at:<br>
example.com<br>
123 Main St, City
</address>

Links and Navigation

<!-- Basic link -->
<a href="https://example.com">Visit Example.com</a>
<!-- Link to local page -->
<a href="/about.html">About Us</a>
<!-- Link with target -->
<a href="https://example.com" target="_blank" rel="noopener">Open in new tab</a>
<!-- Link to section on same page -->
<a href="#section2">Jump to Section 2</a>
<h2 id="section2">Section 2</h2>
<!-- Email link -->
<a href="mailto:[email protected]">Email Us</a>
<!-- Phone link -->
<a href="tel:+1234567890">Call Us</a>
<!-- Download link -->
<a href="document.pdf" download>Download PDF</a>
<!-- Navigation with aria labels for accessibility -->
<nav aria-label="Main navigation">
<ul>
<li><a href="/" aria-current="page">Home</a></li>
<li><a href="/products">Products</a></li>
<li><a href="/services">Services</a></li>
<li><a href="/contact">Contact</a></li>
</ul>
</nav>

Lists

<!-- Unordered list -->
<ul>
<li>First item</li>
<li>Second item</li>
<li>Third item</li>
</ul>
<!-- Ordered list -->
<ol>
<li>First step</li>
<li>Second step</li>
<li>Third step</li>
</ol>
<!-- Ordered list with custom type -->
<ol type="A">  <!-- A, B, C... -->
<li>Item A</li>
<li>Item B</li>
</ol>
<ol type="i">  <!-- i, ii, iii... -->
<li>Item i</li>
<li>Item ii</li>
</ol>
<!-- Description list -->
<dl>
<dt>HTML</dt>
<dd>HyperText Markup Language - used for structure</dd>
<dt>CSS</dt>
<dd>Cascading Style Sheets - used for styling</dd>
</dl>
<!-- Nested lists -->
<ul>
<li>Fruits
<ul>
<li>Apples</li>
<li>Bananas</li>
<li>Oranges</li>
</ul>
</li>
<li>Vegetables
<ul>
<li>Carrots</li>
<li>Broccoli</li>
</ul>
</li>
</ul>

Images and Media

<!-- Basic image -->
<img src="image.jpg" alt="Description of image" width="500" height="300">
<!-- Responsive image with srcset -->
<img 
src="small.jpg" 
srcset="small.jpg 300w, medium.jpg 600w, large.jpg 900w"
sizes="(max-width: 300px) 300px, (max-width: 600px) 600px, 900px"
alt="Responsive image"
>
<!-- Figure with caption -->
<figure>
<img src="diagram.jpg" alt="Diagram showing process">
<figcaption>Figure 1: Process workflow diagram</figcaption>
</figure>
<!-- Video -->
<video controls width="640" height="360">
<source src="video.mp4" type="video/mp4">
<source src="video.webm" type="video/webm">
<track src="subtitles.vtt" kind="subtitles" srclang="en" label="English">
Your browser doesn't support video.
</video>
<!-- Audio -->
<audio controls>
<source src="audio.mp3" type="audio/mpeg">
<source src="audio.ogg" type="audio/ogg">
Your browser doesn't support audio.
</audio>
<!-- Iframe (embed other content) -->
<iframe 
src="https://www.example.com/map" 
width="600" 
height="450" 
style="border:0;" 
allowfullscreen="" 
loading="lazy">
</iframe>

Tables

<table>
<caption>Monthly Sales Report</caption>
<thead>
<tr>
<th>Month</th>
<th>Sales</th>
<th>Profit</th>
</tr>
</thead>
<tbody>
<tr>
<td>January</td>
<td>$10,000</td>
<td>$2,500</td>
</tr>
<tr>
<td>February</td>
<td>$12,000</td>
<td>$3,000</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>Total</td>
<td>$22,000</td>
<td>$5,500</td>
</tr>
</tfoot>
</table>
<!-- Table with colspan and rowspan -->
<table>
<tr>
<th colspan="2">Contact Information</th>
</tr>
<tr>
<td rowspan="2">John Doe</td>
<td>[email protected]</td>
</tr>
<tr>
<td>555-1234</td>
</tr>
</table>

Forms

<form action="/submit" method="POST" enctype="multipart/form-data">
<!-- Text input -->
<div>
<label for="name">Name:</label>
<input type="text" id="name" name="name" required 
placeholder="Enter your name" maxlength="50">
</div>
<!-- Email input -->
<div>
<label for="email">Email:</label>
<input type="email" id="email" name="email" required 
placeholder="[email protected]">
</div>
<!-- Password -->
<div>
<label for="password">Password:</label>
<input type="password" id="password" name="password" 
minlength="8" required>
</div>
<!-- Number input -->
<div>
<label for="age">Age:</label>
<input type="number" id="age" name="age" min="18" max="120">
</div>
<!-- Telephone -->
<div>
<label for="phone">Phone:</label>
<input type="tel" id="phone" name="phone" 
pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" 
placeholder="123-456-7890">
</div>
<!-- URL -->
<div>
<label for="website">Website:</label>
<input type="url" id="website" name="website" 
placeholder="https://example.com">
</div>
<!-- Date -->
<div>
<label for="birthdate">Birthdate:</label>
<input type="date" id="birthdate" name="birthdate">
</div>
<!-- Time -->
<div>
<label for="appt-time">Appointment time:</label>
<input type="time" id="appt-time" name="appt-time">
</div>
<!-- Color -->
<div>
<label for="favcolor">Favorite color:</label>
<input type="color" id="favcolor" name="favcolor" value="#ff0000">
</div>
<!-- Range -->
<div>
<label for="volume">Volume:</label>
<input type="range" id="volume" name="volume" min="0" max="100" value="50">
</div>
<!-- Checkbox -->
<div>
<input type="checkbox" id="subscribe" name="subscribe" checked>
<label for="subscribe">Subscribe to newsletter</label>
</div>
<!-- Radio buttons -->
<div>
<p>Gender:</p>
<input type="radio" id="male" name="gender" value="male">
<label for="male">Male</label>
<input type="radio" id="female" name="gender" value="female">
<label for="female">Female</label>
<input type="radio" id="other" name="gender" value="other">
<label for="other">Other</label>
</div>
<!-- Select dropdown -->
<div>
<label for="country">Country:</label>
<select id="country" name="country">
<option value="">Select a country</option>
<option value="us">United States</option>
<option value="ca">Canada</option>
<option value="uk">United Kingdom</option>
</select>
</div>
<!-- Multi-select -->
<div>
<label for="interests">Interests:</label>
<select id="interests" name="interests" multiple size="3">
<option value="coding">Coding</option>
<option value="design">Design</option>
<option value="marketing">Marketing</option>
</select>
</div>
<!-- Textarea -->
<div>
<label for="message">Message:</label>
<textarea id="message" name="message" rows="4" cols="50" 
placeholder="Enter your message here..."></textarea>
</div>
<!-- File upload -->
<div>
<label for="file">Upload file:</label>
<input type="file" id="file" name="file" accept="image/*,.pdf">
</div>
<!-- Hidden input -->
<input type="hidden" name="user_id" value="12345">
<!-- Buttons -->
<div>
<button type="submit">Submit Form</button>
<button type="reset">Reset Form</button>
<button type="button" onclick="alert('Clicked!')">Click Me</button>
</div>
</form>
<!-- Fieldset and legend for grouping -->
<fieldset>
<legend>Personal Information</legend>
<label for="fname">First name:</label>
<input type="text" id="fname" name="fname"><br>
<label for="lname">Last name:</label>
<input type="text" id="lname" name="lname"><br>
</fieldset>
<!-- Datalist for autocomplete -->
<label for="browser">Choose a browser:</label>
<input list="browsers" id="browser" name="browser">
<datalist id="browsers">
<option value="Chrome">
<option value="Firefox">
<option value="Safari">
<option value="Edge">
</datalist>
<!-- Progress and meter -->
<label for="progress">Progress:</label>
<progress id="progress" value="70" max="100">70%</progress>
<label for="disk">Disk usage:</label>
<meter id="disk" value="0.6" min="0" max="1" low="0.5" high="0.8" optimum="0.2">60%</meter>

Semantic HTML5 Elements

<!-- Header - introductory content -->
<header>
<h1>Website Title</h1>
<nav>...</nav>
</header>
<!-- Navigation - major navigation blocks -->
<nav>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/blog">Blog</a></li>
</ul>
</nav>
<!-- Main - primary content of the page -->
<main>
<article>...</article>
</main>
<!-- Article - self-contained composition -->
<article>
<header>
<h2>Article Title</h2>
<p>Published on <time datetime="2024-03-12">March 12, 2024</time></p>
</header>
<p>Article content...</p>
<footer>
<p>Written by Author</p>
</footer>
</article>
<!-- Section - thematic grouping of content -->
<section>
<h2>Section Heading</h2>
<p>Section content...</p>
</section>
<!-- Aside - tangentially related content -->
<aside>
<h3>Related Articles</h3>
<ul>
<li><a href="#">Article 1</a></li>
</ul>
</aside>
<!-- Footer - footer for a section or page -->
<footer>
<p>&copy; 2024 Company Name</p>
<address>[email protected]</address>
</footer>
<!-- Time - machine-readable date/time -->
<time datetime="2024-03-12T14:30">March 12, 2024 at 2:30 PM</time>
<!-- Mark - highlighted text -->
<p>This is <mark>important</mark> text.</p>
<!-- Details and summary - collapsible content -->
<details>
<summary>Click to expand</summary>
<p>Hidden content revealed when expanded.</p>
</details>
<!-- Figure and figcaption -->
<figure>
<img src="chart.jpg" alt="Data visualization">
<figcaption>Figure 1: Quarterly sales data</figcaption>
</figure>

2. CSS Basics

CSS Syntax and Selectors

/* Basic syntax */
selector {
property: value;
another-property: value;
}
/* Element selectors */
p {
color: blue;
font-size: 16px;
}
h1 {
font-family: Arial, sans-serif;
text-align: center;
}
/* Class selectors */
.highlight {
background-color: yellow;
font-weight: bold;
}
.button {
display: inline-block;
padding: 10px 20px;
background-color: #007bff;
color: white;
text-decoration: none;
border-radius: 5px;
}
/* ID selectors */
#header {
background-color: #333;
color: white;
padding: 20px;
}
#main-content {
max-width: 1200px;
margin: 0 auto;
}
/* Universal selector */
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
/* Attribute selectors */
input[type="text"] {
border: 1px solid #ccc;
padding: 8px;
}
a[href^="https"] {
color: green;
}
a[href$=".pdf"] {
background-image: url('pdf-icon.png');
}
/* Descendant selector */
div p {
color: gray;
}
/* Child selector */
ul > li {
list-style: none;
}
/* Adjacent sibling selector */
h2 + p {
font-weight: bold;
}
/* General sibling selector */
h2 ~ p {
color: #666;
}
/* Pseudo-classes */
a:hover {
color: red;
text-decoration: underline;
}
a:visited {
color: purple;
}
a:active {
color: orange;
}
button:focus {
outline: 2px solid blue;
}
input:required {
border-color: red;
}
input:disabled {
background-color: #eee;
}
li:first-child {
font-weight: bold;
}
li:last-child {
border-bottom: none;
}
li:nth-child(even) {
background-color: #f5f5f5;
}
li:nth-child(3) {
color: blue;
}
p:first-of-type {
font-size: 1.2em;
}
/* Pseudo-elements */
p::first-line {
font-weight: bold;
}
p::first-letter {
font-size: 2em;
float: left;
margin-right: 5px;
}
::selection {
background-color: yellow;
color: black;
}
.bullet::before {
content: "• ";
color: red;
}
.price::after {
content: " USD";
font-size: 0.8em;
}

Colors and Units

/* Color values */
.color-examples {
/* Named colors */
color: red;
color: blue;
color: transparent;
/* Hexadecimal */
color: #ff0000;        /* Red */
color: #00ff00;        /* Green */
color: #0000ff;        /* Blue */
color: #f00;           /* Shorthand red */
color: #fff;           /* Shorthand white */
color: #ff0000cc;      /* With alpha (RGBA hex) */
/* RGB / RGBA */
color: rgb(255, 0, 0);
color: rgba(255, 0, 0, 0.5);
color: rgb(255 0 0 / 50%);
/* HSL / HSLA */
color: hsl(0, 100%, 50%);
color: hsla(0, 100%, 50%, 0.5);
color: hsl(0 100% 50% / 50%);
/* CurrentColor */
color: currentColor;
/* System colors (rarely used) */
color: Canvas;
color: ButtonFace;
}
/* Units */
.units {
/* Absolute units */
width: 100px;           /* Pixels */
width: 1in;             /* Inches */
width: 1cm;             /* Centimeters */
width: 1mm;             /* Millimeters */
width: 1pt;             /* Points (1/72 inch) */
width: 1pc;             /* Picas (12 points) */
/* Relative units */
font-size: 1.2em;       /* Relative to parent font-size */
font-size: 1.2rem;      /* Relative to root font-size */
width: 50vw;            /* Relative to viewport width */
height: 50vh;           /* Relative to viewport height */
width: 50%              /* Relative to parent width */
font-size: 2vmin;       /* 2% of smaller viewport dimension */
font-size: 2vmax;       /* 2% of larger viewport dimension */
/* Viewport percentages */
width: 100vw;           /* Full viewport width */
height: 100vh;          /* Full viewport height */
width: 50svw;           /* Small viewport width */
width: 50lvw;           /* Large viewport width */
/* Container queries units */
width: 50cqw;           /* 50% of container width */
/* Calculations */
width: calc(100% - 40px);
height: calc(50vh - 60px);
font-size: calc(1rem + 2vw);
}

Typography

/* Font properties */
.typography {
/* Font family */
font-family: Arial, Helvetica, sans-serif;
font-family: 'Times New Roman', Times, serif;
font-family: 'Courier New', Courier, monospace;
font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
/* Font size */
font-size: 16px;
font-size: 1.2rem;
font-size: 120%;
/* Font weight */
font-weight: normal;    /* 400 */
font-weight: bold;      /* 700 */
font-weight: 100;       /* Thin */
font-weight: 200;       /* Extra Light */
font-weight: 300;       /* Light */
font-weight: 400;       /* Regular */
font-weight: 500;       /* Medium */
font-weight: 600;       /* Semi Bold */
font-weight: 700;       /* Bold */
font-weight: 800;       /* Extra Bold */
font-weight: 900;       /* Black */
/* Font style */
font-style: normal;
font-style: italic;
font-style: oblique 10deg;
/* Font variant */
font-variant: normal;
font-variant: small-caps;
font-variant: all-small-caps;
/* Line height */
line-height: 1.5;       /* Unitless relative to font size */
line-height: 24px;
line-height: 150%;
/* Text transform */
text-transform: uppercase;
text-transform: lowercase;
text-transform: capitalize;
text-transform: none;
/* Text decoration */
text-decoration: underline;
text-decoration: overline;
text-decoration: line-through;
text-decoration: none;
text-decoration: underline wavy red 2px;
/* Text align */
text-align: left;
text-align: right;
text-align: center;
text-align: justify;
/* Text indent */
text-indent: 30px;
text-indent: 10%;
/* Letter spacing */
letter-spacing: 2px;
letter-spacing: 0.1em;
/* Word spacing */
word-spacing: 5px;
/* White space */
white-space: normal;
white-space: nowrap;
white-space: pre;
white-space: pre-wrap;
white-space: pre-line;
/* Word break */
word-break: normal;
word-break: break-all;
word-break: keep-all;
/* Overflow wrap */
overflow-wrap: normal;
overflow-wrap: break-word;
/* Text shadow */
text-shadow: 2px 2px 4px rgba(0,0,0,0.3);
text-shadow: 1px 1px 0 #000, 2px 2px 0 #ccc;
/* Font smoothing (non-standard) */
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
/* Font-face for custom fonts */
@font-face {
font-family: 'MyCustomFont';
src: url('fonts/custom.woff2') format('woff2'),
url('fonts/custom.woff') format('woff');
font-weight: normal;
font-style: normal;
font-display: swap;
}
/* Web-safe font stacks */
.sans-serif {
font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 
Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue', sans-serif;
}
.serif {
font-family: Georgia, 'Times New Roman', Times, serif;
}
.monospace {
font-family: 'Courier New', Courier, monospace;
}

Box Model

/* Box model properties */
.box {
/* Content dimensions */
width: 300px;
height: 200px;
min-width: 100px;
max-width: 500px;
min-height: 50px;
max-height: 400px;
/* Padding */
padding: 20px;                     /* All sides */
padding: 10px 20px;                /* top/bottom left/right */
padding: 5px 10px 15px 20px;       /* top right bottom left */
padding-top: 10px;
padding-right: 15px;
padding-bottom: 20px;
padding-left: 25px;
/* Border */
border: 1px solid black;
border-width: 2px;
border-style: solid;
border-color: #333;
border: 2px dashed red;
border: 3px dotted blue;
border: 4px double green;
border: 5px groove gray;
border: 5px ridge gray;
border: 5px inset gray;
border: 5px outset gray;
border-top: 1px solid black;
border-right: 2px dashed blue;
border-bottom: 3px dotted red;
border-left: 4px double green;
border-radius: 5px;                /* All corners */
border-radius: 10px 20px;          /* top-left/bottom-right top-right/bottom-left */
border-radius: 10px 20px 15px 5px; /* top-left, top-right, bottom-right, bottom-left */
border-radius: 50%;                /* Circle */
/* Margin */
margin: 20px;                      /* All sides */
margin: 10px 20px;                 /* top/bottom left/right */
margin: 5px 10px 15px 20px;        /* top right bottom left */
margin-top: 10px;
margin-right: 15px;
margin-bottom: 20px;
margin-left: 25px;
margin: 0 auto;                    /* Center horizontally */
/* Box sizing */
box-sizing: content-box;           /* Default: width includes only content */
box-sizing: border-box;            /* width includes padding and border */
/* Display */
display: block;                    /* Takes full width, starts new line */
display: inline;                   /* Takes only needed width, flows in text */
display: inline-block;             /* Like inline but can set width/height */
display: none;                     /* Removes from layout */
display: flex;
display: grid;
/* Visibility */
visibility: visible;               /* Default */
visibility: hidden;                /* Hidden but occupies space */
/* Opacity */
opacity: 0.5;                      /* 0 to 1 */
/* Overflow */
overflow: visible;                 /* Default */
overflow: hidden;                  /* Clip content */
overflow: scroll;                  /* Always show scrollbars */
overflow: auto;                    /* Show scrollbars only when needed */
overflow-x: hidden;                /* Horizontal only */
overflow-y: scroll;                /* Vertical only */
/* Box shadow */
box-shadow: 5px 5px 10px rgba(0,0,0,0.3);
box-shadow: 0 0 10px 5px rgba(0,0,255,0.2);
box-shadow: inset 0 0 10px #000;
box-shadow: 3px 3px 0 #000, 6px 6px 0 #ccc;  /* Multiple shadows */
}

Positioning

/* Positioning examples */
.position-examples {
/* Static (default) */
position: static;
/* Relative - positioned relative to normal position */
position: relative;
top: 10px;
left: 20px;
/* Absolute - positioned relative to nearest positioned ancestor */
position: absolute;
top: 0;
right: 0;
bottom: auto;
left: auto;
/* Fixed - positioned relative to viewport */
position: fixed;
top: 20px;
left: 20px;
/* Sticky - toggles between relative and fixed */
position: sticky;
top: 0;
/* Z-index (stacking order) */
z-index: 10;
z-index: -1;
}
/* Common positioning patterns */
.fixed-header {
position: fixed;
top: 0;
left: 0;
width: 100%;
z-index: 1000;
}
.sticky-sidebar {
position: sticky;
top: 20px;
height: fit-content;
}
.modal-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.5);
display: flex;
align-items: center;
justify-content: center;
z-index: 2000;
}
.modal-content {
position: relative;
width: 500px;
background: white;
padding: 20px;
border-radius: 8px;
}
.badge {
position: absolute;
top: -5px;
right: -5px;
background: red;
color: white;
width: 20px;
height: 20px;
border-radius: 50%;
display: flex;
align-items: center;
justify-content: center;
font-size: 12px;
}

Flexbox Layout

/* Flexbox container */
.flex-container {
display: flex;
/* Direction */
flex-direction: row;                    /* Default */
flex-direction: row-reverse;
flex-direction: column;
flex-direction: column-reverse;
/* Wrap */
flex-wrap: nowrap;                       /* Default */
flex-wrap: wrap;
flex-wrap: wrap-reverse;
/* Shorthand for direction and wrap */
flex-flow: row wrap;
/* Justify content (main axis) */
justify-content: flex-start;             /* Default */
justify-content: flex-end;
justify-content: center;
justify-content: space-between;
justify-content: space-around;
justify-content: space-evenly;
/* Align items (cross axis) */
align-items: stretch;                     /* Default */
align-items: flex-start;
align-items: flex-end;
align-items: center;
align-items: baseline;
/* Align content (when items wrap) */
align-content: stretch;                   /* Default */
align-content: flex-start;
align-content: flex-end;
align-content: center;
align-content: space-between;
align-content: space-around;
/* Gap (spacing between items) */
gap: 10px;
gap: 10px 20px;                          /* row-gap column-gap */
row-gap: 15px;
column-gap: 20px;
}
/* Flex items */
.flex-item {
/* Order */
order: 1;                                 /* Lower numbers first */
/* Grow factor */
flex-grow: 0;                             /* Default */
flex-grow: 1;                             /* Take remaining space */
/* Shrink factor */
flex-shrink: 1;                           /* Default */
/* Basis */
flex-basis: auto;                         /* Default */
flex-basis: 200px;
flex-basis: 30%;
/* Shorthand */
flex: 0 1 auto;                            /* Default */
flex: 1;                                   /* flex: 1 1 0 */
flex: 0 0 200px;                           /* Fixed width */
flex: 1 1 300px;
/* Align self (overrides align-items) */
align-self: auto;                          /* Default */
align-self: flex-start;
align-self: flex-end;
align-self: center;
align-self: stretch;
}
/* Common flexbox patterns */
.navbar {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem;
}
.card-grid {
display: flex;
flex-wrap: wrap;
gap: 20px;
}
.card {
flex: 1 1 300px;  /* Grow, shrink, basis */
}
.centered-content {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
.sidebar-layout {
display: flex;
gap: 20px;
}
.sidebar {
flex: 0 0 250px;
}
.main-content {
flex: 1;
}
.footer {
margin-top: auto;  /* Push footer to bottom */
}

Grid Layout

/* Grid container */
.grid-container {
display: grid;
/* Define columns */
grid-template-columns: 200px 200px 200px;          /* Three fixed columns */
grid-template-columns: 1fr 2fr 1fr;                /* Fractional units */
grid-template-columns: repeat(3, 1fr);             /* Three equal columns */
grid-template-columns: 100px 1fr 2fr;
grid-template-columns: minmax(200px, 1fr) 2fr;
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
/* Define rows */
grid-template-rows: 100px 200px auto;              /* Fixed and auto rows */
grid-template-rows: repeat(3, 1fr);
/* Gap */
gap: 20px;
row-gap: 10px;
column-gap: 15px;
/* Justify items (horizontal alignment) */
justify-items: stretch;                            /* Default */
justify-items: start;
justify-items: end;
justify-items: center;
/* Align items (vertical alignment) */
align-items: stretch;                              /* Default */
align-items: start;
align-items: end;
align-items: center;
/* Place items shorthand */
place-items: center stretch;
/* Justify content (when grid smaller than container) */
justify-content: start;                            /* Default */
justify-content: end;
justify-content: center;
justify-content: space-between;
justify-content: space-around;
justify-content: space-evenly;
/* Align content (vertical) */
align-content: start;
align-content: end;
align-content: center;
align-content: space-between;
/* Named grid areas */
grid-template-areas: 
"header header header"
"sidebar main main"
"footer footer footer";
}
/* Grid items */
.grid-item {
/* Grid column placement */
grid-column-start: 1;
grid-column-end: 3;
grid-column: 1 / 3;                               /* Shorthand */
grid-column: 1 / span 2;                           /* Span 2 columns */
grid-column: span 2;                               /* Span without start */
/* Grid row placement */
grid-row: 1 / 3;
grid-row: span 2;
/* Shorthand placement */
grid-area: 1 / 1 / 3 / 3;                           /* row-start / col-start / row-end / col-end */
/* Named grid areas */
grid-area: header;
/* Justify self (horizontal override) */
justify-self: stretch;
justify-self: start;
justify-self: end;
justify-self: center;
/* Align self (vertical override) */
align-self: stretch;
align-self: start;
align-self: end;
align-self: center;
/* Place self shorthand */
place-self: center stretch;
}
/* Named areas usage */
.header { grid-area: header; }
.sidebar { grid-area: sidebar; }
.main { grid-area: main; }
.footer { grid-area: footer; }
/* Responsive grid patterns */
.responsive-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 20px;
}
.masonry-like {
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-auto-rows: minmax(100px, auto);
}
.featured {
grid-column: span 2;
grid-row: span 2;
}
/* Complex grid layouts */
.calendar-grid {
display: grid;
grid-template-columns: repeat(7, 1fr);
gap: 5px;
}
.day-name {
text-align: center;
font-weight: bold;
}
.weekend {
background-color: #f0f0f0;
}
.today {
border: 2px solid blue;
}
/* Dashboard layout */
.dashboard {
display: grid;
grid-template-columns: 250px 1fr 300px;
grid-template-rows: auto 1fr auto;
grid-template-areas:
"header header header"
"sidebar main widgets"
"footer footer footer";
min-height: 100vh;
gap: 20px;
}

Responsive Design

/* Media queries */
/* Mobile first approach */
/* Base styles for mobile */
.container {
width: 100%;
padding: 10px;
}
/* Tablet */
@media screen and (min-width: 768px) {
.container {
width: 750px;
margin: 0 auto;
padding: 20px;
}
.grid {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 20px;
}
}
/* Desktop */
@media screen and (min-width: 1024px) {
.container {
width: 980px;
}
.grid {
grid-template-columns: repeat(3, 1fr);
}
}
/* Large desktop */
@media screen and (min-width: 1200px) {
.container {
width: 1140px;
}
.grid {
grid-template-columns: repeat(4, 1fr);
}
}
/* Print styles */
@media print {
body {
font-size: 12pt;
line-height: 1.5;
color: #000;
background: #fff;
}
.no-print {
display: none;
}
a::after {
content: " (" attr(href) ")";
}
}
/* Orientation specific */
@media (orientation: landscape) {
.landscape-message {
display: block;
}
}
@media (orientation: portrait) {
.portrait-message {
display: block;
}
}
/* Dark mode preference */
@media (prefers-color-scheme: dark) {
body {
background: #1a1a1a;
color: #f0f0f0;
}
a {
color: #8bbfff;
}
}
/* Reduced motion preference */
@media (prefers-reduced-motion: reduce) {
* {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
}
}
/* High contrast mode */
@media (prefers-contrast: high) {
body {
background: #000;
color: #fff;
}
button {
border: 2px solid #fff;
}
}
/* Container queries (modern browsers) */
@container (min-width: 400px) {
.card {
display: flex;
gap: 20px;
}
}
/* Responsive images */
img {
max-width: 100%;
height: auto;
}
/* Responsive typography */
html {
font-size: 16px;
}
@media screen and (min-width: 768px) {
html {
font-size: 18px;
}
}
/* Viewport units with fallback */
.hero {
height: 100vh;
height: 100svh; /* Small viewport height for mobile */
}
/* Responsive hiding/showing */
.mobile-only {
display: block;
}
.desktop-only {
display: none;
}
@media screen and (min-width: 768px) {
.mobile-only {
display: none;
}
.desktop-only {
display: block;
}
}

Animations and Transitions

/* Transitions */
.transition-example {
/* Transition properties */
transition-property: all;
transition-duration: 0.3s;
transition-timing-function: ease;
transition-delay: 0s;
/* Shorthand */
transition: all 0.3s ease;
transition: background-color 0.3s ease-in, transform 0.2s ease-out;
/* Hover effect */
&:hover {
transform: scale(1.1);
background-color: #ff0000;
}
}
/* Timing functions */
.timing-examples {
/* Predefined */
transition: all 0.3s ease;            /* Default */
transition: all 0.3s linear;          /* Constant speed */
transition: all 0.3s ease-in;         /* Slow start */
transition: all 0.3s ease-out;        /* Slow end */
transition: all 0.3s ease-in-out;     /* Slow start and end */
/* Custom cubic-bezier */
transition: all 0.3s cubic-bezier(0.25, 0.1, 0.25, 1);
transition: all 0.3s cubic-bezier(0.68, -0.55, 0.265, 1.55); /* Bounce */
}
/* Keyframe animations */
@keyframes slide-in {
0% {
transform: translateX(-100%);
opacity: 0;
}
100% {
transform: translateX(0);
opacity: 1;
}
}
@keyframes pulse {
0%, 100% {
transform: scale(1);
}
50% {
transform: scale(1.1);
background-color: #ff0000;
}
}
@keyframes spin {
from {
transform: rotate(0deg);
}
to {
transform: rotate(360deg);
}
}
@keyframes fade-in-out {
0%, 100% {
opacity: 0;
}
50% {
opacity: 1;
}
}
/* Animation usage */
.animated-element {
/* Animation properties */
animation-name: slide-in;
animation-duration: 0.5s;
animation-timing-function: ease-out;
animation-delay: 0s;
animation-iteration-count: 1;
animation-direction: normal;
animation-fill-mode: forwards;
animation-play-state: running;
/* Shorthand */
animation: slide-in 0.5s ease-out;
animation: pulse 2s infinite;
animation: spin 2s linear infinite;
/* Multiple animations */
animation: slide-in 0.5s ease-out, pulse 2s 0.5s infinite;
}
/* Transform properties */
.transform-examples {
/* Translate (move) */
transform: translateX(50px);
transform: translateY(100px);
transform: translate(50px, 100px);
transform: translate3d(50px, 100px, 0);
/* Scale */
transform: scale(1.5);
transform: scaleX(2);
transform: scaleY(0.5);
transform: scale(1.5, 0.5);
/* Rotate */
transform: rotate(45deg);
transform: rotateX(45deg);
transform: rotateY(45deg);
transform: rotate3d(1, 1, 0, 45deg);
/* Skew */
transform: skew(10deg);
transform: skewX(10deg);
transform: skewY(10deg);
/* Multiple transforms */
transform: translateX(50px) rotate(45deg) scale(1.2);
/* Transform origin */
transform-origin: center;
transform-origin: top left;
transform-origin: 50% 50%;
}
/* Practical animation examples */
.button-pulse {
animation: pulse 2s infinite;
}
.button-pulse:hover {
animation-play-state: paused;
}
.spinner {
width: 40px;
height: 40px;
border: 4px solid #f3f3f3;
border-top: 4px solid #3498db;
border-radius: 50%;
animation: spin 1s linear infinite;
}
.skeleton-loading {
background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
background-size: 200% 100%;
animation: loading 1.5s infinite;
}
@keyframes loading {
0% {
background-position: 200% 0;
}
100% {
background-position: -200% 0;
}
}
/* Page transitions */
.page-enter {
opacity: 0;
transform: translateX(-100%);
}
.page-enter-active {
opacity: 1;
transform: translateX(0);
transition: opacity 0.3s, transform 0.3s;
}
.page-exit {
opacity: 1;
transform: translateX(0);
}
.page-exit-active {
opacity: 0;
transform: translateX(100%);
transition: opacity 0.3s, transform 0.3s;
}

3. Advanced CSS Concepts

CSS Variables (Custom Properties)

/* Define variables */
:root {
/* Colors */
--primary-color: #007bff;
--secondary-color: #6c757d;
--success-color: #28a745;
--danger-color: #dc3545;
--warning-color: #ffc107;
--info-color: #17a2b8;
--light-color: #f8f9fa;
--dark-color: #343a40;
/* 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;
/* 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-xl: 2rem;
--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 3px 6px rgba(0,0,0,0.15), 0 2px 4px rgba(0,0,0,0.12);
--shadow-lg: 0 10px 20px rgba(0,0,0,0.15), 0 3px 6px rgba(0,0,0,0.10);
--shadow-xl: 0 15px 25px rgba(0,0,0,0.15), 0 5px 10px rgba(0,0,0,0.05);
/* Transitions */
--transition-fast: 0.15s ease;
--transition-normal: 0.3s ease;
--transition-slow: 0.5s 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;
}
/* Using variables */
.button {
background-color: var(--primary-color);
color: white;
padding: var(--spacing-sm) var(--spacing-md);
border-radius: var(--border-radius-md);
transition: all var(--transition-normal);
box-shadow: var(--shadow-sm);
}
.button:hover {
background-color: var(--dark-color);
box-shadow: var(--shadow-md);
}
/* Theme switching with variables */
.dark-theme {
--primary-color: #375a7f;
--secondary-color: #444;
--light-color: #222;
--dark-color: #f8f9fa;
}
/* Component-specific variables */
.card {
--card-padding: var(--spacing-lg);
--card-bg: white;
--card-border-radius: var(--border-radius-md);
padding: var(--card-padding);
background-color: var(--card-bg);
border-radius: var(--card-border-radius);
box-shadow: var(--shadow-sm);
}
.card-dark {
--card-bg: #333;
--card-padding: var(--spacing-xl);
color: white;
}
/* Dynamic variables with JavaScript */
:root {
--mouse-x: 0px;
--mouse-y: 0px;
}
.mouse-follower {
transform: translate(var(--mouse-x), var(--mouse-y));
}
/* Fallback values */
.element {
color: var(--undefined-color, red);  /* Falls back to red */
padding: var(--spacing-md, 1rem);     /* Falls back to 1rem if variable undefined */
}

CSS Functions

/* calc() - calculations */
.calc-examples {
width: calc(100% - 40px);
height: calc(50vh - 60px);
font-size: calc(16px + 0.5vw);
padding: calc(1rem + 1%);
margin: calc(2rem * 2);
line-height: calc(1.5em + 0.2vw);
}
/* min(), max(), clamp() */
.responsive-sizing {
/* min() - chooses the smallest */
width: min(100%, 500px);
/* max() - chooses the largest */
font-size: max(16px, 2vw);
/* clamp() - sets a value between min and max */
font-size: clamp(14px, 2vw, 24px);
width: clamp(300px, 50%, 800px);
/* Practical examples */
padding: clamp(1rem, 3vw, 3rem);
margin: clamp(10px, 2%, 50px);
}
/* attr() - get attribute value */
.tooltip::after {
content: attr(data-tooltip);
position: absolute;
background: black;
color: white;
padding: 4px 8px;
border-radius: 4px;
font-size: 12px;
white-space: nowrap;
}
/* var() - CSS variables (covered above) */
/* url() - resource references */
.url-examples {
background-image: url('image.jpg');
background-image: url('https://example.com/bg.png');
background-image: url('../images/pattern.svg');
cursor: url('custom.cur'), auto;
list-style-image: url('bullet.png');
}
/* gradient functions */
.gradient-examples {
/* Linear gradient */
background: linear-gradient(to right, red, blue);
background: linear-gradient(45deg, #ff0000, #00ff00, #0000ff);
background: linear-gradient(to bottom, rgba(255,0,0,0), rgba(255,0,0,1));
/* Radial gradient */
background: radial-gradient(circle, red, blue);
background: radial-gradient(circle at top left, yellow, orange);
background: radial-gradient(ellipse at center, white 0%, gray 100%);
/* Conic gradient */
background: conic-gradient(red, blue, green);
background: conic-gradient(from 90deg, red, yellow, green);
/* Repeating gradients */
background: repeating-linear-gradient(45deg, red 0px, red 10px, blue 10px, blue 20px);
background: repeating-radial-gradient(circle, red 0px, red 10px, blue 10px, blue 20px);
}
/* filter functions */
.filter-examples {
filter: blur(5px);
filter: brightness(150%);
filter: contrast(200%);
filter: grayscale(100%);
filter: hue-rotate(90deg);
filter: invert(100%);
filter: opacity(50%);
filter: saturate(200%);
filter: sepia(100%);
filter: drop-shadow(2px 4px 6px black);
/* Multiple filters */
filter: contrast(200%) brightness(150%) sepia(50%);
}
/* backdrop-filter (apply to background) */
.backdrop-filter {
backdrop-filter: blur(10px);
backdrop-filter: brightness(60%);
}
/* clip-path */
.clip-examples {
clip-path: circle(50%);
clip-path: ellipse(25% 50%);
clip-path: polygon(50% 0%, 100% 50%, 50% 100%, 0% 50%);
clip-path: inset(10% 20% 30% 40%);
clip-path: path('M0,0 L100,0 L100,100 L0,100 Z');
}
/* shape-outside */
.shape-outside {
float: left;
shape-outside: circle(50%);
shape-outside: polygon(0 0, 100% 0, 100% 100%);
}

CSS Counters

/* Define and use counters */
body {
counter-reset: section 0;  /* Reset counter named 'section' */
counter-reset: chapter 0 section 0 figure 0;  /* Multiple counters */
}
h2 {
counter-increment: section;  /* Increment counter */
}
h2::before {
content: "Section " counter(section) ": ";
color: #666;
font-weight: normal;
}
/* Nested counters */
body {
counter-reset: chapter;
}
h1 {
counter-reset: section;
counter-increment: chapter;
}
h1::before {
content: "Chapter " counter(chapter) ": ";
}
h2 {
counter-increment: section;
}
h2::before {
content: counter(chapter) "." counter(section) " ";
margin-right: 5px;
}
/* Different counter styles */
.styled-counters {
/* Built-in styles */
counter-reset: item;
list-style-type: none;
}
.styled-counters li {
counter-increment: item;
}
.styled-counters li::before {
/* Different counter styles */
content: counter(item) ". ";           /* 1, 2, 3... */
content: counter(item, decimal) ". ";  /* 1, 2, 3... */
content: counter(item, decimal-leading-zero) ". ";  /* 01, 02, 03... */
content: counter(item, lower-roman) ". ";  /* i, ii, iii... */
content: counter(item, upper-roman) ". ";  /* I, II, III... */
content: counter(item, lower-alpha) ". ";  /* a, b, c... */
content: counter(item, upper-alpha) ". ";  /* A, B, C... */
content: counter(item, lower-greek) ". ";  /* Greek letters */
}
/* Counters with different levels */
.content {
counter-reset: figure;
}
.figure {
counter-increment: figure;
}
.figure::after {
content: " (Figure " counter(figure) ")";
}
/* Reset counters in nested elements */
article {
counter-reset: figure;
counter-increment: article;
}
article h2::before {
content: "Article " counter(article) " - ";
}

CSS Inheritance and Specificity

/* Specificity hierarchy (from most to least specific) */
/*
1. Inline styles (style attribute)
2. IDs (#id)
3. Classes, attributes, pseudo-classes (.class, [attr], :hover)
4. Elements and pseudo-elements (div, ::before)
5. Universal selector (*)
*/
/* Specificity examples */
#header { color: red; }                       /* Specificity: 1,0,0 */
.header { color: blue; }                       /* Specificity: 0,1,0 */
div { color: green; }                          /* Specificity: 0,0,1 */
/* More complex specificity */
div#header.main { color: purple; }              /* 1,1,1 */
body div#main p { color: orange; }              /* 1,0,2 */
div:hover { color: pink; }                      /* 0,1,1 */
/* !important - overrides specificity (use sparingly) */
.important {
color: red !important;  /* Overrides almost everything */
}
/* Inheritance */
.parent {
color: blue;
font-family: Arial, sans-serif;
border: 1px solid black;  /* Not inherited */
padding: 10px;            /* Not inherited */
}
/* Child inherits color and font from parent */
.child {
/* color: blue (inherited) */
/* font-family: Arial (inherited) */
/* border: NOT inherited */
}
/* Controlling inheritance */
.child {
/* Explicitly inherit a property */
border: inherit;
/* Use initial value */
color: initial;
/* Reset to default browser style */
all: unset;  /* Resets all properties */
all: revert; /* Reverts to browser defaults */
/* Revert to user-agent styles */
font-size: revert;
}

4. Practical Examples

Modern CSS Reset

/* Modern CSS Reset */
*,
*::before,
*::after {
box-sizing: border-box;
margin: 0;
padding: 0;
}
/* Remove default margin */
body,
h1,
h2,
h3,
h4,
h5,
h6,
p,
figure,
blockquote,
dl,
dd {
margin: 0;
}
/* Remove list styles */
ul,
ol {
list-style: none;
}
/* Set core body defaults */
body {
min-height: 100vh;
text-rendering: optimizeSpeed;
line-height: 1.5;
font-family: system-ui, -apple-system, 'Segoe UI', Roboto, sans-serif;
}
/* Make images easier to work with */
img,
picture {
max-width: 100%;
display: block;
}
/* Inherit fonts for form elements */
input,
button,
textarea,
select {
font: inherit;
}
/* Remove default button styles */
button {
border: none;
background: none;
cursor: pointer;
}
/* Remove animations for reduced motion */
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
scroll-behavior: auto !important;
}
}
/* Better focus styles */
:focus-visible {
outline: 2px solid blue;
outline-offset: 2px;
}

Card Component

.card {
--card-bg: white;
--card-text: #333;
--card-border-radius: 8px;
--card-shadow: 0 2px 4px rgba(0,0,0,0.1);
--card-hover-shadow: 0 4px 8px rgba(0,0,0,0.15);
--card-transition: 0.3s ease;
background: var(--card-bg);
color: var(--card-text);
border-radius: var(--card-border-radius);
box-shadow: var(--card-shadow);
overflow: hidden;
transition: transform var(--card-transition), box-shadow var(--card-transition);
}
.card:hover {
transform: translateY(-4px);
box-shadow: var(--card-hover-shadow);
}
.card__image {
width: 100%;
height: 200px;
object-fit: cover;
}
.card__content {
padding: 1.5rem;
}
.card__title {
font-size: 1.25rem;
font-weight: 600;
margin-bottom: 0.5rem;
}
.card__description {
color: #666;
line-height: 1.6;
margin-bottom: 1rem;
}
.card__footer {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem 1.5rem;
background: #f5f5f5;
border-top: 1px solid #eee;
}
.card__button {
background: var(--primary-color, #007bff);
color: white;
padding: 0.5rem 1rem;
border-radius: 4px;
font-size: 0.875rem;
transition: background-color 0.2s;
}
.card__button:hover {
background: var(--primary-color-dark, #0056b3);
}
/* Card variants */
.card--horizontal {
display: flex;
}
.card--horizontal .card__image {
width: 200px;
height: auto;
}
.card--featured {
--card-bg: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
--card-text: white;
}
/* Responsive card grid */
.card-grid {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
gap: 2rem;
padding: 2rem;
}

Navigation Bar

/* Modern navigation bar */
.nav {
--nav-bg: white;
--nav-text: #333;
--nav-hover: #007bff;
--nav-padding: 1rem 2rem;
background: var(--nav-bg);
color: var(--nav-text);
padding: var(--nav-padding);
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
position: sticky;
top: 0;
z-index: var(--z-index-sticky, 100);
}
.nav__container {
max-width: 1200px;
margin: 0 auto;
display: flex;
justify-content: space-between;
align-items: center;
}
.nav__logo {
font-size: 1.5rem;
font-weight: bold;
text-decoration: none;
color: var(--nav-text);
}
.nav__menu {
display: flex;
gap: 2rem;
list-style: none;
margin: 0;
padding: 0;
}
.nav__link {
color: var(--nav-text);
text-decoration: none;
padding: 0.5rem 0;
position: relative;
transition: color 0.2s;
}
.nav__link:hover,
.nav__link--active {
color: var(--nav-hover);
}
.nav__link::after {
content: '';
position: absolute;
bottom: 0;
left: 0;
width: 0;
height: 2px;
background: var(--nav-hover);
transition: width 0.3s;
}
.nav__link:hover::after,
.nav__link--active::after {
width: 100%;
}
/* Mobile menu */
.nav__toggle {
display: none;
background: none;
border: none;
cursor: pointer;
padding: 0.5rem;
}
@media (max-width: 768px) {
.nav__toggle {
display: block;
}
.nav__menu {
display: none;
position: absolute;
top: 100%;
left: 0;
right: 0;
background: var(--nav-bg);
flex-direction: column;
padding: 1rem;
box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}
.nav__menu--open {
display: flex;
}
}
/* Dropdown menu */
.nav__dropdown {
position: relative;
}
.nav__dropdown-menu {
display: none;
position: absolute;
top: 100%;
left: 0;
background: white;
min-width: 200px;
box-shadow: 0 2px 8px rgba(0,0,0,0.15);
border-radius: 4px;
padding: 0.5rem 0;
}
.nav__dropdown:hover .nav__dropdown-menu {
display: block;
}
.nav__dropdown-item {
display: block;
padding: 0.5rem 1rem;
color: #333;
text-decoration: none;
transition: background-color 0.2s;
}
.nav__dropdown-item:hover {
background: #f5f5f5;
}

Form Styles

/* Modern form styles */
.form {
max-width: 500px;
margin: 0 auto;
padding: 2rem;
background: white;
border-radius: 8px;
box-shadow: var(--shadow-md, 0 4px 6px rgba(0,0,0,0.1));
}
.form__group {
margin-bottom: 1.5rem;
}
.form__label {
display: block;
margin-bottom: 0.5rem;
font-weight: 500;
color: #333;
}
.form__input,
.form__textarea,
.form__select {
width: 100%;
padding: 0.75rem 1rem;
border: 1px solid #ddd;
border-radius: 4px;
font-size: 1rem;
transition: border-color 0.2s, box-shadow 0.2s;
}
.form__input:focus,
.form__textarea:focus,
.form__select:focus {
outline: none;
border-color: var(--primary-color, #007bff);
box-shadow: 0 0 0 3px rgba(0,123,255,0.1);
}
.form__input:invalid,
.form__textarea:invalid {
border-color: var(--danger-color, #dc3545);
}
.form__input:invalid:focus {
box-shadow: 0 0 0 3px rgba(220,53,69,0.1);
}
.form__input:disabled,
.form__textarea:disabled {
background-color: #f5f5f5;
cursor: not-allowed;
}
/* Checkbox and radio */
.form__checkbox-group,
.form__radio-group {
display: flex;
gap: 1.5rem;
align-items: center;
}
.form__checkbox,
.form__radio {
display: flex;
align-items: center;
gap: 0.5rem;
cursor: pointer;
}
.form__checkbox input[type="checkbox"],
.form__radio input[type="radio"] {
width: 1.2rem;
height: 1.2rem;
cursor: pointer;
}
/* Select with custom arrow */
.form__select-wrapper {
position: relative;
}
.form__select-wrapper::after {
content: '▼';
font-size: 0.8rem;
position: absolute;
right: 1rem;
top: 50%;
transform: translateY(-50%);
pointer-events: none;
color: #666;
}
.form__select {
appearance: none;
padding-right: 2.5rem;
}
/* Form actions */
.form__actions {
display: flex;
gap: 1rem;
justify-content: flex-end;
margin-top: 2rem;
}
.form__button {
padding: 0.75rem 1.5rem;
border: none;
border-radius: 4px;
font-size: 1rem;
font-weight: 500;
cursor: pointer;
transition: background-color 0.2s, transform 0.1s;
}
.form__button--primary {
background: var(--primary-color, #007bff);
color: white;
}
.form__button--primary:hover {
background: var(--primary-color-dark, #0056b3);
}
.form__button--secondary {
background: var(--secondary-color, #6c757d);
color: white;
}
.form__button--secondary:hover {
background: #545b62;
}
.form__button:active {
transform: scale(0.98);
}
.form__button:disabled {
opacity: 0.5;
cursor: not-allowed;
}
/* Error messages */
.form__error {
color: var(--danger-color, #dc3545);
font-size: 0.875rem;
margin-top: 0.25rem;
}
/* Success state */
.form__input--success {
border-color: var(--success-color, #28a745);
}
.form__success-message {
color: var(--success-color, #28a745);
font-size: 0.875rem;
margin-top: 0.25rem;
}

Modal Component

/* Modal overlay */
.modal-overlay {
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.5);
display: flex;
align-items: center;
justify-content: center;
z-index: var(--z-index-modal, 1000);
opacity: 0;
visibility: hidden;
transition: opacity 0.3s, visibility 0.3s;
}
.modal-overlay--open {
opacity: 1;
visibility: visible;
}
/* Modal container */
.modal {
background: white;
border-radius: 8px;
width: 90%;
max-width: 500px;
max-height: 90vh;
overflow-y: auto;
box-shadow: var(--shadow-xl, 0 20px 25px -5px rgba(0,0,0,0.1));
transform: scale(0.9);
transition: transform 0.3s;
}
.modal-overlay--open .modal {
transform: scale(1);
}
/* Modal header */
.modal__header {
display: flex;
justify-content: space-between;
align-items: center;
padding: 1rem 1.5rem;
border-bottom: 1px solid #eee;
}
.modal__title {
margin: 0;
font-size: 1.25rem;
font-weight: 600;
}
.modal__close {
background: none;
border: none;
font-size: 1.5rem;
cursor: pointer;
color: #666;
transition: color 0.2s;
}
.modal__close:hover {
color: #333;
}
/* Modal body */
.modal__body {
padding: 1.5rem;
}
/* Modal footer */
.modal__footer {
display: flex;
justify-content: flex-end;
gap: 1rem;
padding: 1rem 1.5rem;
border-top: 1px solid #eee;
}
/* Modal sizes */
.modal--small {
max-width: 300px;
}
.modal--large {
max-width: 800px;
}
.modal--fullscreen {
max-width: none;
width: 100%;
height: 100%;
border-radius: 0;
}

5. Best Practices and Optimization

Performance Optimization

/* Use will-change for animations */
.animated-element {
will-change: transform, opacity;
}
/* Optimize rendering */
.optimize {
contain: content;          /* Optimize rendering */
content-visibility: auto;  /* Skip off-screen content */
contain-intrinsic-size: 0 500px; /* Reserve space for content-visibility */
}
/* Use transform instead of position for animations */
/* Bad */
@keyframes slide-bad {
from { left: 0; }
to { left: 100px; }
}
/* Good */
@keyframes slide-good {
from { transform: translateX(0); }
to { transform: translateX(100px); }
}
/* Minimize repaints */
/* Bad - causes repaint on every frame */
.element-bad {
animation: move 1s infinite;
}
@keyframes move {
from { top: 0; }
to { top: 100px; }
}
/* Good - uses compositor-only properties */
.element-good {
animation: slide 1s infinite;
}
@keyframes slide {
from { transform: translateY(0); }
to { transform: translateY(100px); }
}

Accessibility (a11y)

/* Skip to main content link */
.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;
}
/* Focus indicators */
*:focus-visible {
outline: 2px solid var(--primary-color, #007bff);
outline-offset: 2px;
}
/* Hide visually but keep for screen readers */
.visually-hidden {
position: absolute;
width: 1px;
height: 1px;
padding: 0;
margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap;
border: 0;
}
/* High contrast mode adjustments */
@media (prefers-contrast: high) {
:root {
--primary-color: #0000ff;
--text-color: #000000;
--background-color: #ffffff;
}
button,
a {
border: 2px solid currentColor;
}
}
/* Reduced motion */
@media (prefers-reduced-motion: reduce) {
*,
*::before,
*::after {
animation-duration: 0.01ms !important;
animation-iteration-count: 1 !important;
transition-duration: 0.01ms !important;
scroll-behavior: auto !important;
}
}

CSS Architecture (BEM)

/* Block Element Modifier (BEM) methodology */
/* Block */
.card {
/* Block styles */
}
/* Element (double underscore) */
.card__title {
/* Element styles */
}
.card__image {
/* Element styles */
}
.card__content {
/* Element styles */
}
/* Modifier (double dash) */
.card--featured {
/* Modifier styles */
}
.card__title--large {
/* Element modifier */
}
/* Usage example */
.card.card--featured
.card__image
.card__content
h2.card__title.card__title--large
p.card__description
/* Utility classes */
.text-center { text-align: center; }
.mt-2 { margin-top: 0.5rem; }
.p-4 { padding: 1rem; }
.d-flex { display: flex; }

CSS Modules (with build tools)

/* styles.module.css */
.container {
max-width: 1200px;
margin: 0 auto;
padding: 2rem;
}
.title {
font-size: 2rem;
color: #333;
margin-bottom: 1rem;
}
.titleHighlight {
color: var(--primary-color);
}
.button {
composes: btn from './shared.module.css';
background: var(--primary-color);
color: white;
}

6. Tools and Resources

CSS Preprocessors (Sass/SCSS)

// Variables
$primary-color: #007bff;
$spacing-unit: 8px;
// Nesting
.nav {
background: white;
&__list {
display: flex;
list-style: none;
}
&__item {
margin-right: $spacing-unit * 2;
&:last-child {
margin-right: 0;
}
}
&__link {
color: #333;
&:hover {
color: $primary-color;
}
}
}
// Mixins
@mixin flex-center {
display: flex;
align-items: center;
justify-content: center;
}
@mixin respond-to($breakpoint) {
@if $breakpoint == mobile {
@media (max-width: 768px) { @content; }
} @else if $breakpoint == tablet {
@media (min-width: 769px) and (max-width: 1024px) { @content; }
} @else if $breakpoint == desktop {
@media (min-width: 1025px) { @content; }
}
}
.hero {
@include flex-center;
height: 100vh;
@include respond-to(mobile) {
height: auto;
padding: 2rem;
}
}
// Functions
@function px-to-rem($px) {
@return ($px / 16px) * 1rem;
}
.container {
width: px-to-rem(1200px);
padding: px-to-rem(20px);
}
// Extend/Inheritance
%button-base {
padding: 0.5rem 1rem;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 1rem;
}
.btn-primary {
@extend %button-base;
background: $primary-color;
color: white;
}
.btn-secondary {
@extend %button-base;
background: gray;
color: white;
}

CSS-in-JS (Styled Components)

// Styled Components example
import styled from 'styled-components';
const Button = styled.button`
padding: ${props => props.size === 'large' ? '1rem 2rem' : '0.5rem 1rem'};
background: ${props => props.primary ? '#007bff' : '#6c757d'};
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 1rem;
&:hover {
background: ${props => props.primary ? '#0056b3' : '#545b62'};
}
&:disabled {
opacity: 0.5;
cursor: not-allowed;
}
`;
const Container = styled.div`
max-width: 1200px;
margin: 0 auto;
padding: 2rem;
@media (max-width: 768px) {
padding: 1rem;
}
`;
// Usage
function App() {
return (
<Container>
<Button primary>Click me</Button>
<Button>Secondary</Button>
<Button size="large" primary>Large Primary</Button>
</Container>
);
}

Conclusion

Key Takeaways

  1. HTML provides structure: Semantic elements create meaningful content
  2. CSS handles presentation: Styles make content visually appealing
  3. Separation of concerns: Keep HTML structure separate from CSS styling
  4. Responsive design: Make websites work on all devices
  5. Accessibility: Ensure content is usable by everyone
  6. Performance: Optimize for speed and efficiency

Best Practices Summary

AreaBest Practice
HTMLUse semantic elements, validate code, include alt text
CSSOrganize with methodology (BEM), use variables, minimize specificity
ResponsiveMobile-first approach, use relative units
AccessibilityAdd ARIA labels, maintain color contrast, support keyboard navigation
PerformanceOptimize selectors, use modern layout techniques, minimize repaints
MaintainabilityComment complex code, use consistent naming, create reusable components

Common Pitfalls to Avoid

  1. Not using semantic HTML - Use <div> only when no semantic element fits
  2. Overly specific selectors - Leads to maintainability issues
  3. Not considering accessibility - Makes site unusable for some users
  4. Forgetting responsive design - Site breaks on mobile devices
  5. Using too many fonts - Affects performance and design consistency
  6. Not optimizing images - Slows down page loading
  7. Inline styles instead of classes - Reduces reusability
  8. Not using CSS variables - Makes theme changes difficult

Mastering HTML and CSS is the foundation of web development. These technologies work together to create the structure and style of every website you see. Practice regularly, keep up with new features, and always consider accessibility and performance in your designs.

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/

Leave a Reply

Your email address will not be published. Required fields are marked *


Macro Nepal Helper