Unit1 - Subjective Questions
INT219 • Practice Questions with Detailed Answers
Explain the concept of Semantic HTML. Why is it important in modern web development? Provide three examples of semantic tags introduced in HTML5.
Semantic HTML refers to the use of HTML markup to reinforce the semantics, or meaning, of the information in web pages and web applications rather than merely defining its presentation or look. A semantic element clearly describes its meaning to both the browser and the developer.
Importance:
- Accessibility: Screen readers use semantic tags to help visually impaired users navigate a page significantly better.
- SEO (Search Engine Optimization): Search engines give more weight to contents inside semantic headings and sections, improving page ranking.
- Maintainability: Code is easier to read and understand for other developers.
Examples of HTML5 Semantic Tags:
<header>: Represents introductory content, typically containing a group of introductory aids or navigational aids.<article>: Specifies independent, self-contained content (e.g., a blog post or news story).<footer>: Defines a footer for a document or section, often containing copyright information or contact details.
Describe the HTML5 Document Structure. Explain the purpose of the <!DOCTYPE html>, <html>, <head>, and <body> tags.
A standard HTML5 document follows a specific tree structure that defines the page.
Component Breakdown:
-
<!DOCTYPE html>:- This is not an HTML tag but an instruction to the web browser about what version of HTML the page is written in.
- It triggers 'standard mode' in browsers to render the page correctly according to HTML5 specifications.
-
<html>:- The root element of an HTML page. All other elements must be descendants of this element.
- It usually includes the
langattribute (e.g.,<html lang="en">) for accessibility and search engines.
-
<head>:- Contains meta-information about the document that is not displayed directly on the page.
- Includes the document title, character set declaration (
<meta charset="UTF-8">), links to CSS stylesheets, and scripts.
-
<body>:- Contains the visible page content, such as headings, paragraphs, images, hyperlinks, tables, lists, etc.
Differentiate between the CSS Box Model standard behavior (content-box) and the alternate behavior (border-box). Provide the mathematical formula for calculating the total width of an element in both cases.
The CSS Box Model describes the rectangular boxes generated for elements in the document tree. It consists of: margins, borders, padding, and the actual content.
1. Standard Box Model (box-sizing: content-box)
- This is the default behavior.
- The
widthandheightproperties refer only to the content area. - Padding and border are added outside of the specified width.
- Formula for Total Rendered Width:
2. Alternate Box Model (box-sizing: border-box)
- This is generally preferred in modern layouts.
- The
widthandheightproperties refer to the entire box (content + padding + border). - The browser subtracts padding and borders from the specified width to calculate the content width automatically.
- Formula for Total Rendered Width:
(Note: Content Width becomes )
Explain CSS Specificity and how it determines which styles are applied when multiple rules match an element. How is specificity calculated?
Specificity is the algorithm used by browsers to determine which CSS declaration is the most relevant to an element, which in turn determines the property value to apply. If two selectors apply to the same element, the one with higher specificity wins.
Calculation Hierarchy:
Specificity is often represented as a 3-column value :
- Column A (ID Selectors): Increments by 1 for every ID (
#id). - Column B (Classes, Attributes, Pseudo-classes): Increments by 1 for every class (
.class), attribute ([type="text"]), or pseudo-class (:hover). - Column C (Type Selectors and Pseudo-elements): Increments by 1 for every element name (
div,h1) or pseudo-element (::before).
Rules:
- Inline styles (inside HTML
style="...") override almost everything else (often considered distinct from the specificity score or having a strictly higher tier). - The universal selector
*has a specificity of . - The
!importantrule overrides normal specificity calculations.
Example:
#header h11 ID, 1 Type =.main .title2 Classes =- Since , the first rule applies.
Describe the different values of the CSS position property. How do relative, absolute, fixed, and sticky differ?
The position property specifies the type of positioning method used for an element.
-
static(Default): The element is positioned according to the normal flow of the document.top,bottom,left, andrighthave no effect. -
relative: The element is positioned relative to its normal position. Moving it usingtoporleftdoes not affect the layout of surrounding elements (the space it originally occupied is preserved). -
absolute: The element is removed from the normal document flow. It is positioned relative to its nearest positioned ancestor (an ancestor with a position other thanstatic). If no such ancestor exists, it is placed relative to the initial containing block (<html>). -
fixed: The element is removed from the document flow and positioned relative to the browser viewport. It stays in the same place even when the page is scrolled. -
sticky: A hybrid of relative and fixed. The element is treated asrelativeuntil it crosses a specified threshold (e.g.,top: 0), at which point it is treated asfixed.
Discuss the CSS Flexbox layout module. Explain the roles of the Main Axis and the Cross Axis.
Flexbox (Flexible Box Layout) is a one-dimensional layout method for laying out items in rows or columns. It excels at distributing space between items in an interface and aligning capabilities.
The Axes:
Flexbox operates on two axes:
-
Main Axis:
- Defined by the
flex-directionproperty (default isrow). - If
flex-direction: row, the main axis runs horizontally (left to right). - If
flex-direction: column, the main axis runs vertically (top to bottom). - Alignment along this axis is controlled by
justify-content.
- Defined by the
-
Cross Axis:
- Runs perpendicular to the Main Axis.
- If the main axis is
row, the cross axis is vertical. - Alignment along this axis is controlled by
align-items(for single lines) oralign-content(for multi-line flex containers).
Compare and contrast CSS Grid and Flexbox. When should you use one over the other?
Comparison:
| Feature | CSS Grid | Flexbox |
|---|---|---|
| Dimensionality | Two-dimensional (Columns AND Rows) | One-dimensional (Columns OR Rows) |
| Focus | Layout-first (Structure) | Content-first (Flow) |
| Overlapping | Easy to overlap items intentionally | Difficult to overlap items |
| State | Best for overall page layout | Best for aligning components inside containers |
Usage Recommendations:
- Use Flexbox when: You have a set of items (like a navigation bar, a list of buttons, or a single row of cards) and you want to space them out evenly or align them centrally.
- Use Grid when: You need precise control over both rows and columns simultaneously, such as a full webpage layout with a header, sidebar, main content, and footer, or a complex image gallery.
What are Form Input Controls in HTML5? List five different types of <input> elements and their specific use cases.
Form input controls are interactive elements that allow users to enter data which can be sent to a server for processing.
Five types of <input> elements:
<input type="text">: A single-line text field.- Use case: Names, usernames, or short addresses.
<input type="password">: A text field that obscures the characters entered.- Use case: Passwords or sensitive PINs.
<input type="email">: A text field that automatically validates that the input is a properly formatted email address.- Use case: Email subscription forms or login.
<input type="radio">: Allows selection of only one option from a related set.- Use case: Gender selection, Yes/No questions.
<input type="checkbox">: Allows selection of zero or more options from a set.- Use case: "Accept Terms and Conditions" or selecting multiple interests.
Explain the syntax and usage of CSS Media Queries. How are they essential for Responsive Web Design?
Media Queries allow developers to apply CSS styles only when specific conditions are met, such as the viewport width, screen resolution, or device orientation.
Syntax:
css
@media media-type and (condition) {
/ CSS rules /
}
Example:
css
@media screen and (max-width: 768px) {
body {
background-color: lightblue;
}
}
Role in Responsive Design:
- Breakpoints: They create "breakpoints" where the layout changes to adapt to the screen size (e.g., switching from a 3-column desktop layout to a 1-column mobile layout).
- Adaptability: They ensure content is readable on smartphones, tablets, and desktops without horizontal scrolling or zooming.
- Resource Optimization: They can be used to load different background images for high-resolution (Retina) screens compared to standard screens.
Describe the implementation of Multimedia Elements in HTML5 using <audio> and <video> tags. Include mention of attributes like controls, autoplay, and source.
HTML5 introduced native support for audio and video without requiring third-party plugins (like Flash).
1. The <video> Element:
Embeds video content. It often contains one or more <source> tags to ensure cross-browser compatibility.
html
<video width="320" height="240" controls poster="thumbnail.jpg">
<source src="movie.mp4" type="video/mp4">
<source src="movie.ogg" type="video/ogg">
Your browser does not support the video tag.
</video>
2. The <audio> Element:
Embeds sound content.
html
<audio controls>
<source src="audio.mp3" type="audio/mpeg">
Your browser does not support the audio element.
</audio>
Key Attributes:
controls: Display playback controls (play/pause button, volume, seek bar).autoplay: Begins playback automatically when the page loads (often restricted by modern browsers for sound).loop: Replays the file once finished.muted: Mutes the audio output by default.poster(Video only): Shows an image before the video starts.
What are Git and GitHub? Explain the fundamental difference between a local repository and a remote repository.
Definitions:
- Git: A distributed version control system (VCS) used to track changes in source code during software development. It runs locally on your machine.
- GitHub: A cloud-based hosting service for Git repositories. It provides a web interface, collaboration tools (pull requests, issues), and backup for code.
Difference between Local and Remote:
| Feature | Local Repository | Remote Repository |
|---|---|---|
| Location | Stored on the developer's personal computer (hard drive). | Stored on a centralized server (e.g., GitHub, GitLab). |
| Access | Only the user of that computer can access it. | Accessible by authorized team members over the internet. |
| Purpose | Used for making changes, experimenting, and committing work privately. | Used as the "source of truth" for sharing code and integrating team changes. |
| Interaction | No network required. | Requires git push to upload and git pull to download changes. |
Explain the Git Workflow involving the three states: Working Directory, Staging Area, and Repository.
Git manages files through three primary trees/areas:
-
Working Directory (Working Tree):
- This is the actual directory on your computer where you edit files.
- Files here can be in a "modified" or "untracked" state.
- These changes are not yet recorded in version history.
-
Staging Area (Index):
- A buffer between the working directory and the repository.
- When you run
git add <file>, you move changes here. - It allows you to curate exactly what you want to include in the next snapshot (commit).
-
Local Repository (HEAD):
- This is the
.gitdirectory where Git permanently stores the metadata and object database. - When you run
git commit, the files in the Staging Area are saved here as a permanent snapshot with a hash ID.
- This is the
Flow: Edit File Staging Area Local Repository.
Define CSS Pseudo-classes and Pseudo-elements. Provide examples for each.
Pseudo-classes:
- Definition: A keyword added to a selector that specifies a special state of the selected element.
- Syntax: Starts with a single colon (
:). - Examples:
:hover: Applies styles when the user hovers over an element.:nth-child(2): Selects the second child of a parent.:focus: Applies when an input element is selected.
Pseudo-elements:
- Definition: A keyword added to a selector that lets you style a specific part of the selected element, or insert content that doesn't exist in the HTML.
- Syntax: Starts with a double colon (
::) in CSS3 (though single colon is often supported for backward compatibility). - Examples:
::before: Inserts content before the element's actual content.::first-line: Styles only the first line of a block of text.::placeholder: Styles the placeholder text of an input field.
Explain the Mobile-First Approach in responsive web design. Why is it considered a best practice?
Mobile-First Approach is a design and development philosophy where the layout is designed for mobile devices (smallest screens) first, and then enhanced for larger screens (tablets, desktops) using media queries (typically min-width queries).
Why it is a Best Practice:
- Content Prioritization: Mobile screens have limited space, forcing developers to prioritize the most important content. This leads to cleaner, more focused designs on all devices.
- Performance: Mobile-first CSS often loads fewer overrides. You start with the simplest styles (base) and add complexity only for devices that can handle it, rather than loading complex desktop styles and overriding them for mobile.
- User Experience: With the majority of web traffic coming from mobile devices, optimizing the experience for these users is critical for retention and SEO.
- Simpler Code: It avoids the complexity of writing "desktop-only" styles that have to be undone for mobile views.
Discuss the different types of CSS Combinators. How do Descendant, Child, Adjacent Sibling, and General Sibling combinators differ?
Combinators explain the relationship between the selectors.
-
Descendant Combinator (space):
div p- Selects all
<p>elements inside<div>, regardless of how deep they are nested.
- Selects all
-
Child Combinator (
>):div > p- Selects all
<p>elements that are direct children of<div>. It does not select grandchildren.
- Selects all
-
Adjacent Sibling Combinator (
+):div + p- Selects the
<p>element that is placed immediately after the<div>element. They must share the same parent.
- Selects the
-
General Sibling Combinator (
~):div ~ p- Selects all
<p>elements that are siblings of<div>and appear anywhere after it (not necessarily immediately).
- Selects all
Explain the significance of CSS Variables (Custom Properties) in modern CSS workflows. How are they declared and used?
CSS Variables, formally known as Custom Properties, allow developers to store specific values to be reused throughout a document. They are entities defined by CSS authors that contain specific values.
Significance:
- Maintainability: You can change a color or size in one place (the definition), and it updates everywhere.
- Readability: Semantically named variables (e.g.,
--main-brand-color) are easier to understand than hex codes. - Dynamic Changes: Unlike preprocessor variables (Sass/Less), CSS variables can be updated dynamically via JavaScript or Media Queries.
Syntax:
-
Declaration: Usually defined in the
:rootpseudo-class for global scope.
css
:root {
--main-color: #3498db;
--padding-std: 10px;
} -
Usage: Accessed using the
var()function.
css
button {
background-color: var(--main-color);
padding: var(--padding-std);
}
What are the essential Git commands required to initialize a repository, save changes, and resolve merge conflicts? List and explain at least 5 commands.
-
git init: Initializes a new, empty Git repository in the current directory. It creates the hidden.gitfolder. -
git status: Displays the state of the working directory and the staging area. It shows which files are modified, staged, or untracked. -
git add [file](orgit add .): Adds changes in the working directory to the staging area. This prepares the changes for the next commit. -
git commit -m "message": Captures a snapshot of the project's currently staged changes. The message should describe what changed. -
git push origin [branch_name]: Uploads the local repository content to a remote repository. -
git merge [branch_name]: Combines the specified branch's history into the current branch. If conflicts occur (same line modified differently), Git pauses and asks the user to manually resolve the conflict in the file.
Differentiate between Block-level, Inline-level, and Inline-block elements in CSS relative to the display property.
1. Block-level Elements (display: block)
- Behavior: Starts on a new line and takes up the full width available (stretches to the left and right as far as it can).
- Dimensions: You can respect
width,height,margin, andpaddingproperties. - Examples:
<div>,<p>,<h1>,<section>.
2. Inline-level Elements (display: inline)
- Behavior: Does not start on a new line; it only takes up as much width as necessary.
- Dimensions:
widthandheightproperties have no effect. Top/bottom margins and padding exist but do not push surrounding elements vertically. - Examples:
<span>,<a>,<b>.
3. Inline-block Elements (display: inline-block)
- Behavior: Flows with the text like an inline element (does not start on a new line), but allows you to set dimensions.
- Dimensions: Resects
width,height,margin, andpaddinglike a block element. - Use Case: Creating navigation bars or grids without using float.
Explain the concept of CSS Units. Distinguish between Absolute Units (px) and Relative Units (em, rem, %, vh, vw).
Absolute Units:
- Pixel (
px): The most common unit. It maps to a fixed number of pixels on the screen (though technically "CSS pixels" vary by device density). It does not scale based on user settings or parent element font sizes. It offers precise control but less flexibility.
Relative Units:
%(Percentage): Relative to the parent element's property (e.g.,width: 50%is half the parent's width).em: Relative to the font-size of the element itself (or the parent if used on font-size). Compoundingems in nested elements can be complex.rem(Root EM): Relative to the font-size of the root element (<html>). This is preferred for accessibility and consistency in responsive typography.vw/vh: Relative to 1% of the viewport's width or height, respectively. Useful for full-screen hero sections.
Describe Modern CSS Workflows. What is the role of CSS Preprocessors (like SASS/SCSS) and Post-processors in development?
Modern CSS workflows involve tools that extend standard CSS to make it more maintainable, programmatic, and cross-browser compatible.
1. CSS Preprocessors (e.g., SASS, LESS):
- They introduce features not natively supported in CSS (historically), such as variables, nesting, mixins (reusable code blocks), and mathematical operations.
- The code is written in
.scssor.lessfiles and "compiled" into standard CSS files that the browser can read. - Benefit: Drastically reduces code repetition and improves organization.
2. CSS Post-processors (e.g., PostCSS, Autoprefixer):
- These tools parse standard CSS and transform it after it has been written (or compiled).
- Role: A common use case is Autoprefixer, which automatically adds vendor prefixes (e.g.,
-webkit-,-moz-) to CSS rules to ensure compatibility with older browser versions based on Can I Use data.