Introduction
Open in the Padhaiko app1.1 Overview of web applications and evolution of web architecture
A web application is a client-server software application that executes business logic, manages dynamic state, and persists data across networks, accessed by users through a standard web browser. Unlike a traditional static website that serves pre-composed HTML, CSS, and image files directly from a filesystem, a web application processes user input, interacts with relational or non-relational databases, executes backend logic, and dynamically synthesizes responses.
Web Application vs. Static Website
A static website delivers identical, pre-rendered content (HTML/CSS/assets) to all users directly from storage media or Content Delivery Networks (CDNs), without server-side processing or dynamic database queries. A web application is an interactive software program executed across browser and server runtimes, featuring bidirectional user communication, session handling, state management, role-based authentication, and transaction processing.
Evolution of Web Architecture
Web architecture has progressed through four distinct architectural generations to satisfy expanding enterprise demands for responsiveness, scalability, maintainability, and user experience:
- First Generation: Static and CGI Web (Web 1.0, Early 1990s): Early web architectures relied on simple file servers delivering static HyperText Markup Language (HTML) documents via the HyperText Transfer Protocol (HTTP). When dynamic behavior was required, web servers invoked external executable scripts using the Common Gateway Interface (CGI). Each incoming HTTP request spawned a new operating system process (Perl, C, or Shell script), executed the query, streamed generated HTML back to the browser, and terminated. This model suffered severe performance bottlenecks due to excessive operating system process-creation overhead and zero memory sharing between requests.
- Second Generation: Server-Side Rendered Dynamic Web (Web 2.0, Late 1990s to 2000s): The introduction of in-process application servers and embedded scripting engines (such as PHP, Active Server Pages (ASP), JavaServer Pages (JSP), and Apache modules like
mod_php) eliminated per-request process creation. Requests were handled by persistent worker threads. The architecture standardized around the classic LAMP stack (Linux, Apache, MySQL, PHP/Python/Perl). Every user interaction (such as submitting a form or clicking pagination) triggered a full-page reload cycle: the server executed database queries, composed an entirely new HTML document on the fly, and transmitted the full payload across the network. - Third Generation: Single Page Applications (SPAs) and RESTful Web Services (2010s): Driven by browser runtime enhancements (high-performance JavaScript V8 engines, ECMAScript standards, and the W3C XMLHttpRequest / Fetch API), web applications separated presentation from backend logic. The server transitioned into a headless provider of RESTful APIs transmitting raw JSON or XML data. The browser downloaded an initial minimal HTML shell and a bundled JavaScript payload (using frameworks such as React, Angular, or Vue). Client-side routers intercepted URL navigation, fetched structured data asynchronously in the background via AJAX/Fetch, and dynamically updated specific Document Object Model (DOM) subtrees without reloading the page.
- Fourth Generation: JAMstack, Micro-Frontends, and Serverless Edge Architectures (2020s to Present): Modern web systems combine the performance advantages of pre-rendered static content with dynamic runtime flexibility. The JAMstack (JavaScript, APIs, Pre-rendered Markup) pre-compiles pages at build time using Static Site Generation (SSG) and hydrates them with client-side JavaScript. Hybrid frameworks (such as Next.js, Remix, and Nuxt) blend Server-Side Rendering (SSR), Incremental Static Regeneration (ISR), and Client-Side Rendering (CSR). Concurrently, cloud architectures have evolved toward Serverless functions (AWS Lambda, Cloudflare Workers) deployed to edge CDN nodes worldwide, reducing latency by executing business logic in close physical proximity to the user.
| Architectural Attribute | Web 1.0 (Static & CGI) | Web 2.0 (Server-Side Rendered) | Web 3.0 / SPAs (Client-Side Rendered) | Modern Hybrid / JAMstack |
|---|---|---|---|---|
| Primary Execution Location | Web server file-system / CGI | Server-side template engine | Client browser JavaScript engine | Distributed Edge + Browser hydration |
| Data Exchange Format | Raw HTML documents | Fully rendered HTML pages | JSON / Protocol Buffers via REST/GraphQL | Pre-rendered HTML + JSON payloads |
| Page Navigation Experience | Full-page reload | Full-page reload | Seamless client-side route transitions | Instant pre-fetched page transitions |
| State Management | Stateless, file-based | Server-side sessions (Cookies/Session ID) | Client-side stores (Redux, Context) + JWT | Hybrid (Edge KV, JWT, Local cache) |
| Initial Page Load Latency | Very fast (static files) | Moderate (server processing latency) | Slow (large JavaScript bundles to parse) | Extremely fast (cached static edge HTML) |
| Subsequent Route Latency | Slow (fresh document fetch) | Slow (full document re-fetch) | Extremely fast (only raw JSON fetched) | Instant (pre-cached chunks and assets) |
Multi-Tier Web Application Architecture
Enterprise web applications are structured into distinct logical tiers to maintain separation of concerns, improve horizontal scalability, and isolate security boundaries:
[ User Agent / Client Tier ]
- Web Browser (HTML5, CSS3, JavaScript, SPA Frameworks, Mobile Web)
- Responsibilities: Rendering UI, capturing user events, input pre-validation
|
| HTTP / HTTPS (JSON, Form-Data, WebSockets)
v
[ Application / Logic Tier ]
- Web Server (Nginx, Apache) -> Reverse Proxy, SSL Termination, Static Cache
- Application Server (Django, Node.js, Spring Boot, ASP.NET)
- Responsibilities: Authentication, Authorization, Routing, Business Rules, ORM
|
| Database Protocols (TCP/IP, Connection Pooling)
v
[ Data / Persistence Tier ]
- Relational Databases (PostgreSQL, MySQL) & NoSQL Stores (MongoDB, Redis)
- Responsibilities: ACID transactions, persistent indexing, query optimization- Presentation Tier (Client Layer): The interface executed inside the client browser. It translates application state into visual representations using HTML and CSS, collects user inputs, performs immediate client-side validation, and dispatches asynchronous requests to the application tier.
- Application Tier (Business Logic Layer): Hosted on centralized or distributed servers. It authenticates identity, authorizes permissions, enforces domain-specific business rules, processes algorithmic workloads, coordinates transactions, and maps data between persistence schemas and client representations.
- Data Tier (Storage Layer): Manages enterprise persistent state. It guarantees data durability, enforces referential integrity constraints, executes indexed queries, and manages cache coherency across disk and in-memory caches.
1.2 Client-server architecture, HTTP, HTTPS, URLs, DNS, web browsers
Web applications rely on distributed networking foundations governed by standardized protocols across the Internet protocol suite.
Client-Server Architecture
The client-server model is a distributed computing structure that partitions tasks between service providers (servers) and service requesters (clients).
- The client initiates communication sessions by formulating and sending request messages over a network socket.
- The server passively listens on a designated transport-layer port (such as TCP port 80 for HTTP or 443 for HTTPS), accepts incoming connections, parses request payloads, executes backend routines, and streams structured response messages back across the connection.
- The interaction follows a strict request-response paradigm: the server does not send unsolicited data to the client unless persistent bidirectional protocols (such as WebSockets or Server-Sent Events) are explicitly negotiated.
Uniform Resource Locators (URLs) and URIs
A Uniform Resource Identifier (URI) is a compact sequence of characters that identifies an abstract or physical resource. A Uniform Resource Locator (URL) is a specific subset of URI that specifies the primary access mechanism (network location and protocol) for retrieving the resource.
https://engineering.tu.edu.np:443/academics/courses?sem=5&type=regular#syllabus
\___/ \____________________/ \___/ \________________/ \____________/ \______/
| | | | | |
Scheme Hostname Port Path Query String Fragment- Scheme (Protocol): Declares the protocol used to access the resource (e.g.,
http,https,ftp,ws). It determines the default transport port, security handshake, and syntax rules. - Hostname (Domain or IP Address): Identifies the host server providing the service. It can be a fully qualified domain name (FQDN) resolved by DNS, or a literal IPv4 (
192.168.1.1) or IPv6 address ([2001:db8::1]). - Port: An integer between 1 and 65535 indicating the transport-layer TCP port. If omitted, standard defaults apply: port 80 for HTTP and port 443 for HTTPS.
- Path: Hierarchical string identifying the specific file, resource endpoint, or route handler within the server namespace (e.g.,
/academics/courses). - Query String: Begins with a question mark (
?) containing key-value pairs delimited by ampersands (&), such assem=5&type=regular. It passes non-hierarchical parameters to the server endpoint. - Fragment Identifier: Begins with a hash symbol (
#). It is processed exclusively by the client browser to scroll to an internal anchor or maintain client-side routing state; it is never transmitted to the web server in the HTTP request line.
Domain Name System (DNS)
The Domain Name System (DNS) is a hierarchical, decentralized naming system that translates human-friendly domain names (e.g., tu.edu.np) into numerical Internet Protocol (IP) addresses required for routing network packets (e.g., 103.10.235.4).
[ Web Browser ]
| 1. Query: "tu.edu.np"
v
[ Recursive DNS Resolver (ISP / 8.8.8.8) ]
| 2. Ask Root Server (".")
v
[ Root DNS Nameserver ] ----> 3. Refers to ".np" ccTLD Server
|
| 4. Ask TLD Server
v
[ TLD Nameserver (".np") ] -> 5. Refers to Authoritative Server for "tu.edu.np"
|
| 6. Ask Authoritative Server
v
[ Authoritative DNS Server ] -> 7. Returns A Record: 103.10.235.4
|
+-----------------------> 8. Returns IP to Browser (and caches result)Key DNS Resource Record types utilized in web deployment:
- A Record: Maps a domain name directly to an IPv4 address (32-bit).
- AAAA Record: Maps a domain name directly to an IPv6 address (128-bit).
- CNAME (Canonical Name): Aliases one domain name to another canonical domain name (e.g.,
www.site.comtosite.com). - MX (Mail Exchange): Directs domain email delivery to designated mail servers.
- TXT Record: Holds arbitrary human or machine-readable text, vital for domain ownership verification, SPF, and DKIM email security.
HyperText Transfer Protocol (HTTP)
HTTP is an application-layer, stateless protocol operating over TCP/IP. It defines the structured syntax of messages exchanged between browsers and web servers.
HTTP Message Structure
Both requests and responses share a four-part textual architecture:
- Start Line: In requests, the Request Line contains the method, target path, and protocol version (e.g.,
GET /index.html HTTP/1.1). In responses, the Status Line contains the protocol version, numeric status code, and reason phrase (e.g.,HTTP/1.1 200 OK). - Headers: Key-value pairs providing metadata about client capabilities, payload encoding, cookies, caching directives, and security policies (e.g.,
Host: tu.edu.np,Content-Type: application/json). - Empty Line: A mandatory Carriage Return and Line Feed (
\r\n) separating headers from the body. - Message Body (Payload): Optional binary or textual data (e.g., form submissions, JSON objects, HTML documents, or image data).
Standard HTTP Methods
HTTP defines standard verbs indicating the desired action to be performed on a target resource. These methods are categorized by two critical properties:
- Safety: A method is safe if it does not alter resource state on the server (read-only operations).
- Idempotence: A method is idempotent if executing it multiple times consecutively produces the exact same server state as executing it once.
| HTTP Method | Primary Purpose | Safe? | Idempotent? | Typical Request Body? |
|---|---|---|---|---|
| GET | Retrieve a representation of a specified resource | Yes | Yes | No |
| HEAD | Retrieve only HTTP headers identical to GET, without body | Yes | Yes | No |
| POST | Submit data to be processed; create a new subordinate resource | No | No | Yes (Form / JSON) |
| PUT | Replace the complete target resource with the uploaded payload | No | Yes | Yes (Complete entity) |
| PATCH | Apply partial modifications to an existing resource | No | No | Yes (Delta instructions) |
| DELETE | Remove the target resource from the server | No | Yes | Rarely |
| OPTIONS | Describe communication options and CORS capabilities | Yes | Yes | No |
HTTP Status Codes
The server indicates request execution outcomes through three-digit status codes grouped into five distinct classes:
- 1xx (Informational): Request received, continuing process (e.g.,
101 Switching Protocolsfor WebSocket upgrades). - 2xx (Success): Action successfully received, understood, and accepted.
200 OK: Standard success response with payload.201 Created: Resource successfully created (common after POST/PUT), accompanied by aLocationheader.204 No Content: Action fulfilled successfully, but the response body is intentionally empty (common for DELETE).
- 3xx (Redirection): Further action required by client to complete the request.
301 Moved Permanently: Target resource assigned a new permanent URI. Search engines transfer SEO weight.302 Found: Temporary redirection to a different URI.304 Not Modified: Cached client copy is still fresh; saves bandwidth by transmitting zero body.
- 4xx (Client Errors): Request contains syntax errors or cannot be fulfilled due to client fault.
400 Bad Request: Server cannot process request due to malformed syntax or invalid payload.401 Unauthorized: Authentication required; valid credentials missing or rejected.403 Forbidden: Authenticated client lacks authorization privileges for the requested action.404 Not Found: Server cannot locate resource matching the requested URI.422 Unprocessable Entity: Syntax is correct, but semantic instructions contain validation errors.
- 5xx (Server Errors): Server failed to fulfill an apparently valid request.
500 Internal Server Error: Generic unhandled exception on the server runtime.502 Bad Gateway: Reverse proxy received an invalid response from upstream application server.503 Service Unavailable: Server currently unable to handle request due to overload or maintenance.504 Gateway Timeout: Upstream server failed to respond to the gateway within configured timeout window.
Protocol Evolution: HTTP/1.1 vs. HTTP/2 vs. HTTP/3
- HTTP/1.0: Opened a separate TCP three-way handshake for every resource request, leading to massive latency.
- HTTP/1.1: Introduced persistent connections (
Connection: keep-alive) and chunked transfer encoding, but suffered from Head-of-Line (HoL) blocking at the application layer: requests over a single connection had to be processed sequentially in strict FIFO order. - HTTP/2: Introduced binary framing, header compression using HPACK, and true connection multiplexing: multiple concurrent requests and responses are interleaved simultaneously as binary frames over a single TCP connection, eliminating application-level HoL blocking.
- HTTP/3: Replaced TCP with QUIC (Quick UDP Internet Connections) over UDP. It solves transport-layer TCP Head-of-Line blocking (packet loss in one stream no longer stalls unrelated streams) and supports zero-round-trip connection establishment (0-RTT).
HTTPS (HTTP Secure) and Transport Layer Security (TLS)
HTTPS tunnels standard HTTP message traffic through an encrypted cryptographic channel established by Transport Layer Security (TLS) (formerly SSL). It guarantees three fundamental security tenets:
- Confidentiality: Eavesdroppers cannot read intercepted plaintext traffic (protecting credentials, personal records, and session cookies).
- Integrity: Digital signatures and Message Authentication Codes (MACs) ensure data cannot be modified or corrupted in transit without immediate detection.
- Authentication: Server identity is cryptographically validated using X.509 Digital Certificates signed by trusted third-party Certificate Authorities (CAs), preventing Man-in-the-Middle (MitM) impersonation.
The TLS 1.3 handshake establishes mutual cryptographic session keys in a single round-trip (1-RTT) using ephemeral Diffie-Hellman key exchange, ensuring Perfect Forward Secrecy (PFS).
Web Browser Architecture and the Critical Rendering Path
A modern web browser is a multi-process operating environment composed of key architectural subsystems:
- User Interface: Address bar, back/forward navigation, bookmarks, and refresh controls.
- Browser Engine: Marshals actions between UI and rendering engine.
- Rendering Engine (Layout Engine): Parses HTML/CSS and draws pixels to screen (e.g., Blink in Chrome, Gecko in Firefox, WebKit in Safari).
- JavaScript Engine: Compiles and executes script code via Just-In-Time (JIT) compilers (e.g., Google V8, SpiderMonkey, JavaScriptCore).
- Networking Subsystem: Handles socket connections, HTTP/HTTPS caching, and DNS resolution.
- UI Backend: Platform-native graphics routines for windowing and basic drawing primitives.
- Data Persistence: Client-side storage facilities (Cookies, Web Storage, IndexedDB, Cache API).
Critical Rendering Path (CRP)
The Critical Rendering Path is the sequential series of steps a web browser executes to convert raw HTML, CSS, and JavaScript bytes received from the network into rendered pixels on the visual display:
- DOM Construction: Parsing HTML bytes into characters, tokens, nodes, and assembling the Document Object Model (DOM) tree.
- CSSOM Construction: Parsing CSS rules into style nodes and building the CSS Object Model (CSSOM) tree (render-blocking).
- Render Tree Generation: Combining visible DOM nodes with computed CSSOM styles into the Render Tree (omits non-visual elements like
<head>anddisplay: none). - Layout (Reflow): Calculating exact geometric dimensions, coordinates, and positions for every visible box on the viewport.
- Paint (Rasterization): Filling in actual pixels (colors, borders, text, shadows) into bitmap layers.
- Compositing: Layering drawn surfaces on the GPU according to z-index and stacking contexts to render the final frame.
1.3 Html basics: Syntax, tags, attributes, forms and inputs, tables, lists, multimedia, semantic HTML5 elements
HyperText Markup Language (HTML) is the standard declarative markup language defining the structural scaffolding and semantic meaning of documents rendered on the World Wide Web.
HTML5 Document Anatomy and Syntax Rules
An HTML document comprises a hierarchical tree of elements, demarcated by opening tags, optional attributes, content, and closing tags. Void elements (such as <img>, <input>, <br>, <meta>, <hr>) possess no closing tags or internal content.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Tribhuvan University Portal</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<header>
<h1>Department of Electronics and Computer Engineering</h1>
</header>
<main>
<p>Welcome to the Web Application Programming academic portal.</p>
</main>
</body>
</html>Key Structural Declarations:
<!DOCTYPE html>: Declares document type as standard HTML5, instructing browsers to render in standards-compliant mode rather than quirks mode.<html lang="en">: Root container element specifying primary language for screen readers and search indexers.<meta charset="UTF-8">: Declares character encoding as UTF-8, covering virtually all international characters and symbols.<meta name="viewport" content="width=device-width, initial-scale=1.0">: Essential for mobile responsiveness; aligns viewport width to device screen width and sets initial zoom scale to 100%.
Semantic HTML5 Elements vs. Non-Semantic Containers
Semantic HTML5 elements convey explicit machine-readable meaning regarding their enclosed content to browsers, assistive technologies (screen readers), and search engine bots.
| Aspect | Semantic Elements | Generic Containers (div / span) |
|---|---|---|
| Meaning & Context | Clearly describes purpose (<nav>, <article>, <aside>, <main>) | Carries zero inherent semantic meaning |
| Accessibility (a11y) | Automatically maps to WAI-ARIA landmark roles for screen reader navigation | Requires manual role="..." and ARIA attributes |
| Search Engine Optimization | Prioritizes content weighting (e.g., <article> vs <footer>) | Search indexers treat contents uniformly |
| Code Maintainability | Clean, self-documenting structural layout | Leads to unmaintainable deeply nested "div soup" |
| Default Styling | Standard block/inline behavior with semantic defaults | Block (<div>) or inline (<span>) with zero styling |
Core Semantic Layout Landmarks:
<header>: Introductory content, brand logos, or global site navigation wrappers.<nav>: Dedicated section containing major navigation link menus.<main>: Central unique content of the document body; there must only be one visible<main>per page.<article>: Self-contained, independently distributable composition (e.g., a blog post, news story, forum comment).<section>: Generic standalone thematic grouping of content, typically introduced by an explicit heading.<aside>: Content tangentially related to the main content (e.g., sidebars, callout boxes, related links).<footer>: Closing section containing copyright, legal links, contact information, and author citations.<figure>and<figcaption>: Encapsulates media (diagrams, photos, code snippets) paired with an explanatory caption.
Lists and Tables
HTML provides structured elements for tabular and sequential information:
- Lists:
- Unordered List (
<ul>): Bulleted list of items (<li>) where order is arbitrary. - Ordered List (
<ol>): Numbered or alphabetical sequence of items (<li>), configurable withstartandtypeattributes. - Description List (
<dl>): Pairs of terms (<dt>) and descriptions (<dd>), ideal for glossaries, metadata, and key-value displays.
- Unordered List (
- Tables: Tables represent two-dimensional structured relational data, composed with semantic row groupings:
<table border="1">
<caption>Institute of Engineering Sem V Examination Schedule</caption>
<thead>
<tr>
<th scope="col">Subject Code</th>
<th scope="col">Course Title</th>
<th scope="col">Marks</th>
</tr>
</thead>
<tbody>
<tr>
<td>ENCT 302</td>
<td>Web Application Programming</td>
<td>80</td>
</tr>
<tr>
<td>ENCT 301</td>
<td>Database Management Systems</td>
<td>80</td>
</tr>
</tbody>
<tfoot>
<tr>
<th scope="row" colspan="2">Total Core Weightage</th>
<td>160</td>
</tr>
</tfoot>
</table>scope="col" and scope="row" explicitly associate header cells with corresponding columns or rows, ensuring full screen-reader accessibility. colspan and rowspan merge adjacent cells horizontally or vertically.
Multimedia Elements: Images, Audio, and Video
Modern HTML delivers native media playback without external browser plugins:
- Images (
<img>): Embeds raster or vector graphics. Requiressrc(file path) andalt(textual description for accessibility and SEO). Featuresloading="lazy"for deferred off-screen image fetching, andsrcsetwithsizesfor responsive image resolution switching. - Audio (
<audio>): Embeds sound streams using child<source>tags specifying fallback codecs (e.g., MP3, OGG). Thecontrolsattribute renders native play, pause, and volume widgets. - Video (
<video>): Embeds video streams withcontrols,poster(preview image),preload, and multiple<source>tags (MP4, WebM).
Forms, Inputs, and HTML5 Validation
Forms constitute the primary user-input mechanism for transmitting data payloads to backend servers:
<form action="/api/v1/students/register" method="POST" enctype="application/x-www-form-urlencoded">
<fieldset>
<legend>Student Registration Form</legend>
<div class="form-group">
<label for="fullName">Full Name:</label>
<input type="text" id="fullName" name="fullName" required minlength="3" maxlength="60" placeholder="e.g. Ramesh Thapa">
</div>
<div class="form-group">
<label for="emailAddr">Campus Email:</label>
<input type="email" id="emailAddr" name="email" required placeholder="[email protected]">
</div>
<div class="form-group">
<label for="userPassword">Password:</label>
<input type="password" id="userPassword" name="password" required minlength="8">
</div>
<div class="form-group">
<label for="semesterSelect">Semester:</label>
<select id="semesterSelect" name="semester">
<option value="5" selected>Fifth Semester</option>
<option value="6">Sixth Semester</option>
</select>
</div>
<div class="form-group">
<label for="remarks">Project Summary:</label>
<textarea id="remarks" name="summary" rows="4" cols="50"></textarea>
</div>
<button type="submit">Complete Registration</button>
</fieldset>
</form>Critical Form Attributes:
action: Destination URL endpoint where collected form data is dispatched.method: HTTP verb (GETappends encoded parameters to URL query string;POSTtransmits data in request body).enctype: MIME encoding format (application/x-www-form-urlencodeddefault for text;multipart/form-datarequired for binary file uploads;text/plainfor raw debugging).<label for="...">: Pairs with an input element'sid. Clicking the text automatically shifts focus to the corresponding control, expanding hit targets on touch devices.
1.4 CSS basics: Selectors, properties, values, box model
Cascading Style Sheets (CSS) is the declarative style language used to describe the visual presentation, formatting, and layout of documents structured in HTML.
Cascading, Specificity, and Inheritance
CSS operates under three foundational conflict-resolution principles when multiple rules target the same element:
- Importance and Origin:
!importantdeclarations override normal declarations. User-agent styles are superseded by user styles, which are superseded by author styles. - Specificity: The weight assigned to a selector rule determining precedence. Specificity is calculated as a four-part vector
(a, b, c, d):a(Inline styles): Styles applied directly viastyle="..."attribute (Weight: 1000).b(IDs): Number of ID selectors such as#header(Weight: 100).c(Classes, attributes, pseudo-classes):.btn,[type="text"],:hover(Weight: 10).d(Elements and pseudo-elements):h1,p,::before,::after(Weight: 1).- The universal selector (
*), combinators (+,>,~, space), and:where()carry zero specificity(0, 0, 0, 0).
- Source Order: When two rules possess identical specificity, the rule appearing latest in the stylesheet wins.
- Inheritance: Properties such as
color,font-family, andline-heightcascade automatically from parent containers to children, whereas layout properties likemargin,padding,border, anddisplaydo not inherit.
CSS Selectors Reference
Selectors define the element matching criteria across the DOM tree:
- Simple Selectors: Element (
div), Class (.card), ID (#main-nav). - Combinators:
- Descendant (
article p): Matches any<p>nested anywhere within<article>. - Child (
ul > li): Matches only direct immediate child<li>of<ul>. - Adjacent Sibling (
h2 + p): Matches<p>immediately preceded by an<h2>. - General Sibling (
h2 ~ p): Matches all<p>sharing the same parent following an<h2>.
- Descendant (
- Attribute Selectors:
input[type="email"],a[href^="https"](starts with),a[href*="tu.edu"](contains substring), suffix selector matching target file extensions. - Pseudo-Classes (State & Structural):
:hover,:focus,:active,:first-child,:last-child,:nth-child(2n+1). - Pseudo-Elements (Generated Content):
::before,::after,::placeholder,::selection.
The CSS Box Model
Every element rendered on an HTML page is represented as a rectangular layout structure consisting of four concentric layers:
+-------------------------------------------------------+
| Margin (Transparent outer clearance between elements) |
| +-----------------------------------------------+ |
| | Border (Solid/dashed line enclosing element) | |
| | +---------------------------------------+ | |
| | | Padding (Inner space around content) | | |
| | | +-------------------------------+ | | |
| | | | Content Area (Text, Images) | | | |
| | | | width x height | | | |
| | | +-------------------------------+ | | |
| | +---------------------------------------+ | |
| +-----------------------------------------------+ |
+-------------------------------------------------------+- Content Area: Contains the actual text, media, or child elements, governed by
widthandheight. - Padding: Transparent spacing surrounding the content inside the border. Clears background color/image.
- Border: Encloses content and padding; styles, widths, and colors are customizable.
- Margin: Transparent spacing outside the border, isolating the element from adjacent sibling elements. Vertical margins of adjacent block elements undergo margin collapsing.
Box-Sizing: content-box vs. border-box
The box-sizing CSS property determines whether padding and border dimensions expand the rendered box width or are contained within the declared width:
| Aspect | content-box (W3C Default) | border-box (Modern Standard) |
|---|---|---|
| Declared Width Applies To | Content area only | Content + Padding + Border combined |
| Rendered Outer Box Width | width + padding_left + padding_right + border_left + border_right | Exact declared width |
| Internal Content Width | Exact declared width | width - (padding_left + padding_right + border_left + border_right) |
| Layout Predictability | Complex; adding padding unexpectedly expands elements, breaking grid percentages | Intuitive; elements consistently occupy declared percentage or pixel widths |
| Standard Best Practice | Deprecated for modern layouts | Globally applied via * { box-sizing: border-box; } |
Display Types and Modern Layouts
The display property controls an element's formatting context:
block: Starts on a new line, expands to 100% of parent width, respects width/height/margins (e.g.,<div>,<p>).inline: Flows within text, does not start a new line; ignores vertical margins and width/height (e.g.,<span>,<a>).inline-block: Flows inline with text, but respects declared width, height, padding, and margins (e.g.,<button>,<input>).none: Completely removes the element from the accessibility tree and visual render tree; occupies zero space.flex: Initiates a one-dimensional Flexbox layout context (rows or columns) with alignment and flexible distribution (justify-content,align-items,flex-grow).grid: Initiates a two-dimensional grid layout context managing rows and columns simultaneously (grid-template-columns,gap).
1.5 CSS framework: Bootstrap
A CSS framework is a pre-prepared software library containing standardized, tested CSS stylesheets and optional JavaScript components. It accelerates development by providing responsive grid systems, accessible UI components, typography scales, and atomic utility classes.
Advantages and Disadvantages of CSS Frameworks
| Dimension | Advantages | Disadvantages |
|---|---|---|
| Development Speed | Pre-built navigation bars, cards, modals, and forms allow rapid prototyping | Over-reliance creates generic "cookie-cutter" website aesthetics |
| Cross-Browser Uniformity | Normalizes CSS resets and vendor prefix discrepancies automatically | Unused framework classes add bloat unless pruned with PurgeCSS |
| Mobile Responsiveness | Built-in mobile-first 12-column flexbox grid handles all viewport sizes | Deeply nested framework classes clutter HTML markup |
| Accessibility (a11y) | Components implement ARIA standards and keyboard focus traps out-of-the-box | Overriding opinionated framework styles requires high CSS specificity |
The Bootstrap 12-Column Responsive Grid System
Bootstrap's layout engine uses a mobile-first 12-column flexbox grid, built upon three primary architectural containers:
- Container (
.containeror.container-fluid): Provides horizontal padding and centers content on screen..containersteps through fixed maximum widths at specific breakpoints, while.container-fluidspans 100% width across all viewports. - Row (
.row): Horizontal wrapper for columns that enforces negative margins to neutralize container padding and ensures column alignment. - Columns (
.col-*): Immediate children of rows. The integer suffix defines how many of the 12 available fractional columns an element occupies.
Bootstrap Breakpoint Tiers:
- Extra Small (
xs): Viewport width < 576px (class prefix:.col-) - Small (
sm): Viewport width >= 576px (class prefix:.col-sm-) - Medium (
md): Viewport width >= 768px (class prefix:.col-md-) - Large (
lg): Viewport width >= 992px (class prefix:.col-lg-) - Extra Large (
xl): Viewport width >= 1200px (class prefix:.col-xl-) - Extra Extra Large (
xxl): Viewport width >= 1400px (class prefix:.col-xxl-)
<div class="container my-4">
<div class="row g-3">
<!-- 12 cols on mobile, 6 cols on tablet, 4 cols on desktop -->
<div class="col-12 col-md-6 col-lg-4">
<div class="card p-3 shadow-sm">
<h5 class="card-title">Engineering Math III</h5>
<p class="card-text">Advanced differential equations and transforms.</p>
<button class="btn btn-primary">Open Subject</button>
</div>
</div>
<div class="col-12 col-md-6 col-lg-4">
<div class="card p-3 shadow-sm">
<h5 class="card-title">Web Application Programming</h5>
<p class="card-text">Client and server web development architectures.</p>
<button class="btn btn-success">Open Subject</button>
</div>
</div>
<div class="col-12 col-md-12 col-lg-4">
<div class="card p-3 shadow-sm">
<h5 class="card-title">Database Systems</h5>
<p class="card-text">Relational queries, ACID transactions, and normalization.</p>
<button class="btn btn-warning">Open Subject</button>
</div>
</div>
</div>
</div>Atomic Utilities in Bootstrap 5
Bootstrap 5 features responsive utility classes for rapid layout styling without writing custom CSS:
- Spacing: Margin (
m-1throughm-5), Padding (p-1throughp-5), Directions (mttop,mbbottom,msstart/left,meend/right,mxhorizontal,myvertical). Auto-centering viamx-auto. - Flexbox Utilities:
d-flex,justify-content-between,align-items-center,flex-column,flex-wrap. - Color & Background:
text-primary,text-muted,bg-light,bg-dark,border,rounded.
Worked Examples
CSS Box Model Dimensions Calculation
A web developer styles a card element with the following CSS declarations: width: 400px; height: 200px; padding: 25px; border: 5px solid #333; margin: 20px;
Calculate:
- The rendered outer box width and the total horizontal footprint occupied in the document layout under the default W3C
box-sizing: content-boxmodel. - The rendered outer box width, the resulting inner content width, and the total horizontal footprint occupied under the modern
box-sizing: border-boxmodel.
Determine the box dimensions under content-box: Under box-sizing: content-box, the CSS width property configures only the central content area.
- Content Width = 400 px
- Horizontal Padding = padding-left + padding-right = 25 px + 25 px = 50 px
- Horizontal Border = border-left + border-right = 5 px + 5 px = 10 px
- Horizontal Margin = margin-left + margin-right = 20 px + 20 px = 40 px
The rendered outer box width (border-edge) is: Rendered Width = Content Width + Horizontal Padding + Horizontal Border Rendered Width = 400 + 50 + 10 = 460 px
The total horizontal layout space (including margins) is: Total Footprint = Rendered Width + Horizontal Margin = 460 + 40 = 500 px
Determine the box dimensions under border-box: Under box-sizing: border-box, the declared CSS width defines the total width up to the outer edge of the border.
- Declared Width = Rendered Width = 400 px
- Horizontal Padding = 25 px + 25 px = 50 px
- Horizontal Border = 5 px + 5 px = 10 px
- Horizontal Margin = 20 px + 20 px = 40 px
The inner content width available for text and images is compressed: Inner Content Width = Declared Width - (Horizontal Padding + Horizontal Border) Inner Content Width = 400 - (50 + 10) = 340 px
The total horizontal layout footprint occupied in the document is: Total Footprint = Declared Width + Horizontal Margin = 400 + 40 = 440 px
- Under
content-box: Rendered box width is 460 px; total horizontal layout footprint is 500 px. - Under
border-box: Rendered box width is 400 px; internal content width shrinks to 340 px; total horizontal layout footprint is 440 px.
End-to-End Web Lifecycle: URL to Rendered Pixels
A student enters the following URL into a web browser: https://engineering.tu.edu.np:443/portal/login?ref=home#form
Trace the complete sequence of network protocols and browser operations executed from the moment the user presses Enter until the login screen is visually presented on the monitor.
URL Parsing and Local Cache Check: The browser parses the string into protocol (https), target hostname (engineering.tu.edu.np), port (443), path (/portal/login), query string (ref=home), and fragment (#form). The fragment #form is retained locally in browser memory and not sent to the server. The browser checks its internal HSTS list (confirming HTTPS), service worker cache, and DNS cache (browser DNS cache, OS cache, /etc/hosts).
DNS Resolution and Socket Establishment: Assuming a DNS cache miss, the OS queries the recursive DNS resolver. The resolver queries the Root DNS servers (.), the .np ccTLD nameserver, and finally the authoritative nameserver for tu.edu.np, which returns the A record IP address (e.g., 103.10.235.4). The browser opens a transport-layer socket by performing a TCP 3-way handshake (SYN -> SYN-ACK -> ACK) with 103.10.235.4 on port 443.
TLS Handshake and Secure Channel Negotiation: Over the established TCP stream, client and server execute the TLS 1.3 handshake:
- Client sends
ClientHellowith supported cipher suites and key share parameters. - Server replies with
ServerHello, presents its X.509 digital certificate signed by a trusted CA, and transmits its key share. - The browser validates certificate authenticity, expiration, and domain name against trusted root certificates stored in the OS/browser trust store.
- Both endpoints derive symmetric encryption session keys. All subsequent data exchange is encrypted.
HTTP Request-Response Transmission: The browser constructs and transmits an HTTP/1.1 or HTTP/2 request:
GET /portal/login?ref=home HTTP/1.1
Host: engineering.tu.edu.np
User-Agent: Mozilla/5.0
Accept: text/html,application/xhtml+xmlThe server reverse proxy (Nginx) terminates TLS, routes the request to the application server (e.g., Django/Node.js), which queries the database, renders the HTML document, and returns: HTTP/1.1 200 OK along with Content-Type: text/html; charset=UTF-8 and the HTML byte stream in the body.
Critical Rendering Path Execution in Browser:
- The browser engine parses HTML bytes into tokens, generating the DOM tree.
- Encountering external
<link rel="stylesheet">, the network subsystem fetchesstyles.cssasynchronously and parses it into the CSSOM tree. - DOM and CSSOM are merged into the Render Tree.
- The engine performs Layout, calculating exact pixel coordinates on the viewport.
- Painting rasterizes colors, borders, and text into bitmap layers.
- Compositing uploads GPU layers to screen.
- Finally, the browser scrolls the viewport down until the element with
id="form"is aligned.
The lifecycle executes: (1) URL parsing, (2) Hierarchical DNS resolution to target IP, (3) TCP three-way handshake on port 443, (4) TLS 1.3 cryptographic handshake validating X.509 certificate, (5) HTTP GET request and 200 OK HTML delivery, (6) Critical Rendering Path (DOM + CSSOM -> Render Tree -> Layout -> Paint -> Composite), and (7) viewport scrolling to the #form fragment anchor.
CSS Specificity Calculation and Cascade Resolution
Evaluate the four CSS rules targeting the hyperlink element <a id="cta-link" class="nav-btn primary" href="/apply">Apply Now</a> nested inside <nav id="top-nav" class="navbar">:
Rule A: #top-nav .nav-btn a { color: blue; } Rule B: nav.navbar a.primary { color: green; } Rule C: #cta-link { color: red; } Rule D: <a ... style="color: purple;">
Calculate the specificity vector (Inline, ID, Class, Element) for Rules A, B, and C. Identify which rule wins the cascade and determines the final rendered color of the hyperlink.
Calculate Specificity Vectors for Rules A, B, and C: Specificity vector format: (a, b, c, d) where:
a= Inline stylesb= Number of ID selectorsc= Number of class, attribute, and pseudo-class selectorsd= Number of element and pseudo-element selectors- Rule A:
#top-nav .nav-btn a- Inline: 0
- IDs: 1 (
#top-nav) - Classes: 1 (
.nav-btn) - Elements: 1 (
a) - Specificity vector =
(0, 1, 1, 1)-> Value score = 1100 + 110 + 1*1 = 111
- Rule B:
nav.navbar a.primary- Inline: 0
- IDs: 0
- Classes: 2 (
.navbar,.primary) - Elements: 2 (
nav,a) - Specificity vector =
(0, 0, 2, 2)-> Value score = 210 + 21 = 22
- Rule C:
#cta-link- Inline: 0
- IDs: 1 (
#cta-link) - Classes: 0
- Elements: 0
- Specificity vector =
(0, 1, 0, 0)-> Value score = 1*100 = 100
Evaluate Cascade Precedence: Comparing Rules A, B, and C:
- Rule B has 0 IDs, so it is eliminated by Rules A and C.
- Rule A
(0, 1, 1, 1)beats Rule C(0, 1, 0, 0)because both have 1 ID, but Rule A has 1 class and 1 element selector.
However, Rule D is declared directly on the element via the style="..." attribute:
- Rule D specificity vector =
(1, 0, 0, 0)(Score = 1000).
Because inline styles possess higher specificity than any external or internal selector rule (unless an external rule applies !important), Rule D supersedes Rules A, B, and C.
Specificity vectors:
- Rule A:
(0, 1, 1, 1)(Score = 111) - Rule B:
(0, 0, 2, 2)(Score = 22) - Rule C:
(0, 1, 0, 0)(Score = 100) - Rule D (Inline):
(1, 0, 0, 0)(Score = 1000)
Rule D wins due to inline style precedence, rendering the link in purple. If Rule D were removed, Rule A would win with specificity (0, 1, 1, 1), rendering it in blue.
Exercises
Practice Exercises — Introduction to Web Architecture
Define the terms Safety and Idempotence in the context of HTTP methods. Classify GET, POST, PUT, and DELETE under both criteria, and explain why choosing the correct method is critical for web caches and web proxies.
Definitions of Safety and Idempotence:
- Safe Methods: HTTP methods that do not alter the server's resource state. They perform read-only queries and produce zero server-side side effects (except harmless logging and analytics).
- Idempotent Methods: HTTP methods where executing the exact same request once produces the identical resource state on the server as executing it multiple times consecutively: f(f(x)) = f(x).
Classification of Core HTTP Methods:
- GET: Safe: YES, Idempotent: YES. Retrieving data does not modify server state; repeating GET produces identical server state.
- POST: Safe: NO, Idempotent: NO. Creates new child resources or triggers transactions. Repeating POST results in duplicate orders, duplicate bank deductions, or duplicate records.
- PUT: Safe: NO, Idempotent: YES. Replaces the entire target resource with the request body. Sending the exact same replacement payload ten times leaves the resource identical to sending it once.
- DELETE: Safe: NO, Idempotent: YES. Removes the target resource. Once deleted, subsequent identical DELETE requests find the resource already gone, leaving the server state unchanged.
Significance for Caches and Web Proxies: Web proxies and browser caches automatically cache responses to safe (GET/HEAD) requests, drastically conserving network bandwidth and reducing server workload. Furthermore, network proxies and browsers can safely auto-retry failed idempotent requests (GET, PUT, DELETE) upon transient TCP connection drops without user risk. In contrast, non-idempotent requests (POST) must never be retransmitted automatically without user confirmation, preventing duplicate billing or double submissions.
Safe methods (GET) produce zero state changes; idempotent methods (GET, PUT, DELETE) produce identical server state whether executed once or repeatedly. Proxies cache safe methods and auto-retry idempotent requests upon network drops, whereas non-idempotent methods (POST) can never be retried automatically without risk of duplicate side effects.
Explain the step-by-step sequence of the Critical Rendering Path (CRP) in modern web browsers. Distinguish between Layout (Reflow) and Painting (Repaint), and state which CSS properties trigger each.
Steps of the Critical Rendering Path:
- DOM Construction: HTML parser converts raw bytes to characters, tokens, and nodes, assembling the Document Object Model tree.
- CSSOM Construction: CSS parser processes stylesheets into the CSS Object Model tree. This operation blocks rendering until complete.
- Render Tree Generation: Intersects DOM and CSSOM to build visible nodes requiring display. Nodes styled with
display: noneand<head>tags are omitted. - Layout (Reflow): Computes geometry (exact position coordinates, width, and height) for every box within the viewport.
- Paint (Repaint): Converts render nodes into visual pixels (drawing text, borders, colors, background images).
- Compositing: Assembles painted GPU layers into final screen output.
Reflow vs. Repaint:
- Layout (Reflow): Occurs when geometric or structural properties change, forcing the browser to recalculate the positions and sizes of affected elements and all their descendants/siblings. Highly CPU-intensive. Triggered by changes to:
width,height,padding,margin,font-size,display,position,top,left. - Painting (Repaint): Occurs when visual appearance changes without altering element geometry or layout footprint. Cheaper than reflow. Triggered by changes to:
color,background-color,visibility,box-shadow,border-color. - Performance Best Practice: Animate only composite-layer properties handled directly by the GPU:
transformandopacity.
The CRP follows: DOM -> CSSOM -> Render Tree -> Layout -> Paint -> Composite. Layout (Reflow) recalculates geometric sizes and positions (triggered by width, margin, display), whereas Paint (Repaint) redraws visual styling without changing geometry (triggered by color, background-color).
Why are semantic HTML5 elements preferred over generic <div> tags? List any five semantic structural elements introduced in HTML5 and describe their intended roles in a web document.
Reasons for Preferring Semantic Elements:
- Accessibility (a11y): Screen readers use semantic landmarks to provide shortcut keyboard navigation for visually impaired users.
- Search Engine Optimization (SEO): Search crawlers weigh
<main>and<article>content higher than boilerplate navigation or footers. - Maintainability and Developer Ergonomics: Self-describing element tags eliminate nested "div soup", accelerating code reviews and team collaboration.
- Consistent Browser Default Styles: Certain semantic tags provide standardized native keyboard focus and interaction behavior.
Five Semantic Structural Elements and Roles:
<header>: Encapsulates introductory content, site branding, logo, search bar, and primary navigation wrappers.<nav>: Designates an explicit navigation section containing major site hyperlinks.<main>: Encloses the dominant, unique content of the document. Only one visible<main>element may exist per page.<article>: Defines an independent, self-contained composition intended for standalone distribution (such as a blog post or news article).<footer>: Contains metadata about the enclosing section or page, including author attribution, copyright statements, and terms of service.
Semantic HTML5 tags improve screen-reader accessibility, SEO indexing, and code maintainability compared to generic <div> tags. Five core elements include <header> (introductory branding), <nav> (navigation links), <main> (central unique page content), <article> (self-contained distributable article), and <footer> (closing legal and author metadata).
Explain how the Bootstrap 12-column grid system works. What is the functional role of the .container, .row, and .col-* classes, and why must columns always be immediate children of rows?
Structure and Operation of the 12-Column Grid: Bootstrap divides every horizontal row into 12 proportional virtual column slices. Developer classes specify how many of these 12 slices a child box spans across responsive breakpoint tiers (e.g., .col-12 spans 100% width, .col-6 spans 50% width, .col-4 spans 33.33% width). If the total column count in a row exceeds 12, the extra columns automatically wrap onto a new line.
Functional Roles of the Core Grid Containers:
.container/.container-fluid: Provides horizontal padding to prevent content from touching the viewport edge and centers the layout on widescreen displays usingmargin-left: auto; margin-right: auto;..row: Serves as a flexbox container (display: flex; flex-wrap: wrap;). Crucially, rows apply negative horizontal margins (e.g.,-15pxon left and right) to neutralize the internal padding of the surrounding.container..col-*: Provides horizontal padding (gutters) to keep column text from colliding.- Why columns must be immediate children of rows: The negative margins of the
.rowand the positive padding of the.colare mathematically matched. Placing non-column elements directly inside a row, or placing columns outside a row, breaks gutter alignment and causes horizontal overflow scrollbars.
Bootstrap's grid partitions horizontal space into 12 flexible columns. Containers provide outer padding, rows apply negative margins to align content, and columns contain gutter padding. Columns must be immediate children of rows so that row negative margins and column positive padding cancel out perfectly, preventing broken layout gutters and horizontal scrolling.
Differentiate between HTTP/1.1, HTTP/2, and HTTP/3 with respect to transport protocol, multiplexing, and Head-of-Line (HoL) blocking.
HTTP/1.1 Characteristics:
- Transport: TCP.
- Protocol Format: Plaintext text-based protocol.
- Multiplexing: None. Supports persistent connections (
keep-alive) and pipelining, but requests over a connection must be answered strictly in FIFO order. - Head-of-Line (HoL) Blocking: Severe application-layer HoL blocking; a slow or heavy server response stalls all subsequent queued requests behind it on that TCP connection.
HTTP/2 Characteristics:
- Transport: TCP.
- Protocol Format: Binary framing layer (headers and data frames).
- Multiplexing: Full bidirectional multiplexing over a single shared TCP connection; requests and responses are interleaved simultaneously. Includes HPACK header compression.
- Head-of-Line (HoL) Blocking: Eliminates application-layer HoL blocking. However, it introduces transport-layer TCP HoL blocking: because all streams share a single TCP socket, an OS-level TCP packet drop stalls all interleaved streams until retransmitted.
HTTP/3 Characteristics:
- Transport: QUIC over UDP.
- Protocol Format: Binary framing with integrated TLS 1.3 cryptographic security.
- Multiplexing: Native stream multiplexing managed directly within the QUIC protocol.
- Head-of-Line (HoL) Blocking: Completely eliminated. A dropped UDP packet affects only the specific stream containing that packet; all other concurrent streams continue processing uninterrupted.
HTTP/1.1 uses plaintext over TCP with severe application-layer HoL blocking. HTTP/2 uses binary multiplexing over TCP, eliminating application HoL blocking but remaining vulnerable to TCP packet-loss HoL blocking. HTTP/3 runs QUIC over UDP, providing true independent multiplexing where packet loss on one stream never stalls other streams.