Unit 3: Cascading Style Sheets - Subjective Questions
CSE326 — Internet Programming • Practice Questions with Detailed Answers
20 questions
Define CSS. Explain the different methods of applying CSS to an HTML document and state their relative advantages.
Cascading Style Sheets (CSS) is a style-sheet language used to control the presentation and layout of HTML documents. It separates the visual design of a web page from its content and structure.
Methods of applying CSS:
- Inline CSS: Styles are written in the
styleattribute of an HTML element, such as<p style="color: red;">Text</p>. It is useful for a unique style but is difficult to maintain and reuse. - Internal CSS: Styles are placed inside a
<style>element in the document's<head>. It is suitable for styling a single page but cannot be shared efficiently across multiple pages. - External CSS: Styles are stored in a separate
.cssfile and linked using<link rel="stylesheet" href="styles.css">. It provides reusability, easier maintenance, browser caching, and consistent design across multiple pages.
External CSS is generally preferred for multi-page websites, while internal and inline CSS are useful for page-specific or element-specific requirements.
Explain the major types of CSS selectors with suitable examples.
CSS selectors identify the HTML elements to which style rules are applied.
- Universal selector:
* { box-sizing: border-box; }selects every element. - Type selector:
p { color: navy; }selects all<p>elements. - Class selector:
.warning { color: red; }selects elements whose class iswarning. - ID selector:
#header { height: 80px; }selects the element whose ID isheader. - Grouping selector:
h1, h2, h3 { font-family: sans-serif; }applies the same rules to several selectors. - Descendant selector:
article p { line-height: 1.6; }selects paragraphs inside an<article>. - Child selector:
nav > a { padding: 8px; }selects links that are direct children of<nav>. - Adjacent sibling selector:
h2 + p { margin-top: 0; }selects the first paragraph immediately after an<h2>. - General sibling selector:
h2 ~ p { color: gray; }selects all matching paragraph siblings after an<h2>.
Selectors can be combined to target elements precisely while avoiding unnecessary classes.
What is CSS specificity? Explain how specificity and the cascade determine which declaration is applied.
Specificity is the priority calculated for a selector when multiple CSS declarations target the same property of the same element.
A useful specificity representation is , where:
- represents inline styles.
- represents ID selectors.
- represents class selectors, attribute selectors, and pseudo-classes.
- represents type selectors and pseudo-elements.
For example, #menu .item a has one ID, one class, and one type selector, giving it higher specificity than .item a.
The browser resolves conflicts in this general order:
- Importance and origin: Important declarations, author styles, user styles, and browser defaults are considered according to cascade rules.
- Cascade layers: Rules in the winning layer are preferred.
- Specificity: The selector with the greater specificity wins.
- Source order: If specificity is equal, the declaration written later wins.
The !important annotation changes normal priority and should be used sparingly because it makes overrides harder to manage. Inherited values are used only when no directly applied declaration supplies the property.
Describe the different ways of specifying colors and backgrounds in CSS.
CSS supports several color representations:
- Named colors:
color: blue; - Hexadecimal:
color: #336699; - RGB and alpha:
color: rgb(51 102 153);andcolor: rgb(51 102 153 / 0.5); - HSL and alpha:
color: hsl(210 50% 40%);andcolor: hsl(210 50% 40% / 0.5); - Special keyword:
color: transparent;
Important background properties include:
background-colorsets a solid background color.background-imageadds an image or gradient.background-repeatcontrols image repetition.background-positionsets the starting position.background-sizecontrols dimensions, with values such ascoverandcontain.background-attachmentdetermines whether the background scrolls.background-clipcontrols the area in which the background is painted.
The background shorthand can set several properties in one declaration, for example background: #222 url("pattern.png") center / cover no-repeat;. Multiple backgrounds can also be listed from front to back, separated by commas.
Distinguish between absolute and relative CSS units. Explain when px, %, em, rem, vw, and vh should be used.
Absolute units have a fixed reference. The most common web unit is px, which represents a CSS pixel. It is useful for borders, icons, and dimensions that need precise visual control.
Relative units depend on another value and are useful for scalable, responsive designs:
%is calculated relative to a property-specific reference, often the containing block's size.emis relative to the current element's computed font size. Forfont-size, it is relative to the parent's font size. Nested use can compound values.remis relative to the root element's font size and provides predictable document-wide scaling.vwequals of the viewport width.vhequals of the viewport height.
For accessible typography, rem is often preferable because it respects the user's root font-size settings. Percentages work well for fluid widths, while viewport units are useful for dimensions tied to the screen. Fixed px values should not be overused for text or major responsive layout dimensions.
Explain how typography and text styling are controlled in CSS. Include important properties and readability considerations.
CSS provides typography and text properties for controlling how written content is displayed.
Font properties:
font-familydefines a prioritized font stack.font-sizecontrols character size.font-weightcontrols thickness, such as400or700.font-styleapplies styles such asitalic.line-heightcontrols spacing between lines.fontis a shorthand for several font properties.
Text properties:
text-aligncontrols horizontal alignment.text-decorationadds or removes lines such as underlines.text-transformchanges capitalization.text-indentindents the first line.text-shadowadds a shadow to text.white-space,overflow-wrap, andword-breakcontrol wrapping and whitespace.text-overflow: ellipsiscan indicate clipped text when used with suitable overflow and whitespace rules.
Readable content should use sufficient color contrast, an appropriate font size, a clear typeface, and a line height commonly around 1.4 to 1.6. Long paragraphs should also have a controlled line length. Underlines should generally remain available for links so that they are recognizable.
Explain the CSS box model. How do content-box and border-box affect the computed size of an element?
Every rendered element can be treated as a rectangular box consisting of:
- Content: The area occupied by text, images, or child elements.
- Padding: Transparent space between the content and border.
- Border: The line surrounding the padding and content.
- Margin: External space separating the element from neighboring elements.
With the default box-sizing: content-box, declared width and height apply only to the content. If horizontal padding values are and , and border widths are and , then:
Margins affect occupied layout space but are not part of the visible box width.
With box-sizing: border-box, the declared width includes the content, padding, and border. This makes layout calculations more predictable. A common rule is *, *::before, *::after { box-sizing: border-box; }.
Vertical margins of normal block elements may collapse in certain situations, meaning the resulting gap can be the larger margin rather than the sum of both margins.
Compare static, relative, absolute, fixed, and sticky positioning in CSS.
The position property determines how an element is placed and whether offset properties such as top, right, bottom, and left affect it.
static: The default. The element remains in normal document flow, and offsets do not apply.relative: The element keeps its original space in normal flow but can be visually offset. It can also establish a containing block for positioned descendants.absolute: The element is removed from normal flow and positioned relative to its nearest positioned ancestor; otherwise, it is positioned relative to an initial containing block.fixed: The element is removed from normal flow and is normally positioned relative to the viewport, so it remains visible during scrolling.sticky: The element behaves like a relatively positioned element until a specified scrolling threshold is reached, after which it behaves like a fixed element within its scroll container.
z-index controls stacking order for positioned elements and other elements that create stacking contexts. Sticky positioning requires an offset such as top: 0 and enough scrollable space to observe the effect.
Describe the Flexbox layout model and explain the properties used to align and distribute flex items.
Flexbox is a one-dimensional layout model designed to arrange items along a main axis and a cross axis. It is enabled using display: flex or display: inline-flex on a container.
Container properties:
flex-directiondefines the main-axis direction usingrow,column, and their reverse forms.flex-wrapcontrols whether items move onto additional lines.justify-contentdistributes items along the main axis.align-itemsaligns items along the cross axis.align-contentdistributes multiple flex lines along the cross axis.gapcreates consistent spacing between items.
Item properties:
flex-growdefines how unused space is shared.flex-shrinkdefines how items shrink when space is insufficient.flex-basisspecifies the initial main size.flexis the shorthand for grow, shrink, and basis.align-selfoverrides cross-axis alignment for one item.orderchanges visual order, although it should not be used to create a misleading keyboard or reading order.
Flexbox is particularly suitable for navigation bars, toolbars, aligned controls, and component-level layouts.
Explain CSS Grid Layout and show how explicit tracks, gaps, and item placement are defined.
CSS Grid is a two-dimensional layout system that controls rows and columns together. A grid formatting context is created with display: grid.
Example:
main { display: grid; grid-template-columns: 240px 1fr; grid-template-rows: auto 1fr; gap: 16px; }
Important concepts and properties include:
grid-template-columnsandgrid-template-rowsdefine explicit tracks.frdistributes available space proportionally.repeat(3, 1fr)creates repeated tracks.minmax(200px, 1fr)sets minimum and maximum track sizes.gap,row-gap, andcolumn-gapprovide spacing between tracks.grid-columnandgrid-rowposition or span items using grid lines.grid-template-areascreates named layout regions.grid-auto-flow,grid-auto-rows, andgrid-auto-columnscontrol implicitly created tracks.justify-items,align-items, andplace-itemsalign content inside grid areas.
A responsive grid can be created with grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));, allowing columns to adjust automatically without a media query.
Compare Flexbox and CSS Grid. Under what circumstances should each layout system be selected?
Flexbox and Grid are complementary layout systems.
Flexbox:
- Primarily one-dimensional, arranging content in a row or column.
- Sizes and aligns items based strongly on their content.
- Well suited to navigation bars, button groups, form controls, and aligning items within a component.
- Makes distribution along one main axis straightforward.
CSS Grid:
- Two-dimensional, controlling rows and columns simultaneously.
- Defines a layout structure first and then places content into it.
- Well suited to page layouts, galleries, dashboards, and repeated card arrangements.
- Supports precise line-based placement, spanning, named areas, and overlapping.
Flexbox should generally be selected when the primary requirement is alignment or distribution in one direction. Grid should be selected when row and column relationships must be controlled together. They are frequently combined, for example by using Grid for the overall page and Flexbox for controls inside each grid region.
Distinguish between pseudo-classes and pseudo-elements. Give examples of their practical use.
A pseudo-class selects an existing element based on its state, position, or relationship. It uses a single colon in modern CSS.
Examples include:
a:hoverselects a link under the pointer.input:focusselects a focused input.button:disabledselects a disabled button.li:first-childselects an element that is the first child of its parent.tr:nth-child(even)selects alternating table rows..field:has(input:invalid)selects a field containing an invalid input where:has()is supported.
A pseudo-element selects or creates a specific part of an element and normally uses two colons.
Examples include:
p::first-linestyles the first formatted line.p::first-letterstyles the first letter..required::after { content: "*"; }generates decorative content after an element.input::placeholderstyles placeholder text.::selectionstyles selected content.
Pseudo-elements generated with ::before and ::after require the content property. Important information should not exist only in generated content because accessibility support may vary.
Explain CSS attribute selectors and demonstrate the operators available for matching attribute values.
Attribute selectors target elements according to the presence or value of an HTML attribute.
[disabled]selects elements that contain thedisabledattribute.[type="email"]selects elements whosetypevalue is exactlyemail.[class~="featured"]matches a whitespace-separated word in an attribute value.[lang|="en"]matchesenor values beginning withen-.[href^="https"]matches values beginning withhttps.[href$=".pdf"]matches values ending with.pdf.[href*="example"]matches values containingexampleanywhere.
An optional flag can control case sensitivity in supported comparisons, for example [type="EMAIL" i], where i requests case-insensitive matching.
Attribute selectors are useful for styling form controls by type, identifying external links, marking downloadable files, and styling elements according to states represented by attributes such as aria-expanded="true".
Describe how HTML forms can be styled with CSS while preserving usability and accessibility.
Forms can be styled consistently by first allowing controls to inherit typography, for example button, input, select, textarea { font: inherit; }.
Important practices include:
- Use associated
<label>elements and provide adequate spacing and readable text. - Set appropriate widths, padding, borders, and background colors on controls.
- Use
accent-colorto style compatible checkboxes and radio buttons. - Use
:focus-visibleto display a strong keyboard focus indicator. - Use
:disabled,:checked,:required,:valid, and:invalidto represent states. - Do not rely only on color to communicate validation errors; include text or another visible indicator.
- Keep controls large enough for touch interaction.
- Preserve sufficient contrast for labels, entered text, placeholders, borders, and focus outlines.
- Avoid removing native appearance unless all interactive states and behaviors are recreated correctly.
A suitable focus rule is input:focus-visible { outline: 3px solid #1565c0; outline-offset: 2px; }. Placeholder text should be treated as a hint rather than a replacement for a persistent label.
What are CSS custom properties? Explain their declaration, scope, inheritance, fallback values, and common applications.
CSS custom properties, commonly called CSS variables, are reusable property values whose names begin with two hyphens.
They are declared and used as follows:
:root { --brand-color: #1565c0; --space-md: 16px; }
.button { background-color: var(--brand-color); padding: var(--space-md); }
Key features include:
- Custom properties participate in the cascade.
- They inherit by default, so descendants can use values declared by ancestors.
- Their scope depends on the selector where they are declared. Variables in
:rootare globally available, while variables on a component can create local overrides. - A fallback can be provided using
var(--unknown-color, black). - Their values can be changed by classes, media queries, pseudo-classes, or JavaScript.
Common uses include design tokens for colors, spacing, typography, component configuration, and light or dark themes. Unlike preprocessor variables, custom properties remain available at runtime and can respond directly to the cascade.
Explain the principles of responsive web design and the role of media queries, fluid layouts, and responsive media.
Responsive web design enables a page to adapt to different screen sizes, orientations, user preferences, and input capabilities.
Its main principles are:
- Mobile-first design: Start with styles for smaller screens and add enhancements using conditions such as
@media (min-width: 48rem). - Fluid layouts: Use percentages, flexible Grid or Flexbox tracks,
min(),max(), andclamp()instead of unnecessary fixed widths. - Responsive media: Use
img { max-width: 100%; height: auto; }, and usesrcsetor<picture>when different image resources are needed. - Media queries: Apply styles based on features such as width, orientation, hover capability, color scheme, or reduced-motion preference.
- Content-based breakpoints: Choose breakpoints where the layout stops working rather than targeting specific device names.
- Viewport configuration: Use
<meta name="viewport" content="width=device-width, initial-scale=1">so mobile browsers use the device width correctly.
Responsive interfaces must also keep text readable, controls touch-friendly, navigation usable, and horizontal scrolling limited to components that genuinely require it.
Describe CSS animations using @keyframes. Explain the major animation properties and accessibility considerations.
CSS animations allow an element to move through multiple style states without requiring JavaScript. The states are declared with @keyframes.
Example:
@keyframes fade-in { from { opacity: 0; } to { opacity: 1; } }
.notice { animation: fade-in 400ms ease-out 1 both; }
Major properties include:
animation-nameidentifies the keyframes.animation-durationspecifies the time for one cycle.animation-timing-functioncontrols acceleration, such aslinear,ease, orcubic-bezier().animation-delaydelays the start.animation-iteration-countcontrols repetition.animation-directioncan alternate or reverse playback.animation-fill-modecontrols styles before and after playback.animation-play-statepauses or resumes an animation.animationis the shorthand property.
For performance, animating transform and opacity is generally preferable to repeatedly changing layout-related properties. Motion should not be distracting, and a prefers-reduced-motion: reduce media query should remove or reduce nonessential animation for users who request it.
What are CSS transitions? Explain their properties and illustrate how a transition is triggered.
A CSS transition gradually changes an animatable property from its current value to a new value when a state change occurs.
Example:
.button { background-color: #1565c0; transform: translateY(0); transition: background-color 200ms ease, transform 200ms ease; }
.button:hover { background-color: #0d47a1; transform: translateY(-2px); }
The transition is triggered when the button starts or stops matching :hover.
Transition properties are:
transition-propertyselects the properties to animate.transition-durationspecifies how long the change takes.transition-timing-functiondefines the rate of change.transition-delaypostpones the transition.transitioncombines these values in shorthand form.
Only animatable properties can transition. Values such as display: none generally cannot be interpolated in the traditional transition model. Listing specific properties is preferable to transition: all because it prevents unintended animations and makes performance behavior clearer.
Differentiate between CSS transitions and CSS animations with respect to triggering, control, complexity, and use cases.
CSS transitions interpolate between an old value and a new value. They normally require a trigger such as :hover, :focus, a class change, or a JavaScript-driven style change.
CSS animations use named @keyframes and can begin automatically when their animation rules apply. They can define many intermediate stages and repeat independently.
Key differences are:
- Stages: A transition primarily moves between two states, while an animation can include many keyframe stages.
- Triggering: Transitions require a property-value change; animations can start when an element receives an animation name.
- Repetition: Animations provide
animation-iteration-count; transitions do not repeat automatically. - Direction and playback: Animations support alternate direction, fill modes, and paused states.
- Typical uses: Transitions suit hover feedback, expanding controls, and small state changes. Animations suit loaders, entrance sequences, and multi-stage motion.
Both should use restrained durations, favor performant properties such as transform and opacity, and respect the prefers-reduced-motion user preference.
Design and explain a responsive card gallery using CSS Grid, custom properties, pseudo-classes, transitions, and a media query.
A responsive gallery can combine several CSS features:
:root { --gap: 1rem; --accent: #1565c0; }
.gallery { display: grid; grid-template-columns: repeat(auto-fit, minmax(16rem, 1fr)); gap: var(--gap); }
.card { padding: 1rem; border: 1px solid #ccc; transition: transform 200ms ease, border-color 200ms ease; }
.card:hover, .card:focus-within { transform: translateY(-4px); border-color: var(--accent); }
.card::before { content: ""; display: block; height: 0.25rem; background: var(--accent); }
@media (max-width: 30rem) { .gallery { grid-template-columns: 1fr; } }
@media (prefers-reduced-motion: reduce) { .card { transition: none; } }
Explanation:
repeat(auto-fit, minmax(...))creates as many columns as fit while maintaining a practical minimum card width.gapand custom properties provide consistent, reusable spacing and color values.:hovergives pointer feedback, while:focus-withinprovides similar feedback when a keyboard user focuses a link or control inside the card.::beforecreates a decorative accent without extra HTML.- The width media query guarantees a single column on very narrow screens.
- The reduced-motion query respects accessibility preferences by removing nonessential movement.
The HTML source order should remain logical so that visual reflow does not harm keyboard navigation or reading order.
Define CSS. Explain the different methods of applying CSS to an HTML document and state their relative advantages.
Cascading Style Sheets (CSS) is a style-sheet language used to control the presentation and layout of HTML documents. It separates the visual design of a web page from its content and structure.
Methods of applying CSS:
- Inline CSS: Styles are written in the
styleattribute of an HTML element, such as<p style="color: red;">Text</p>. It is useful for a unique style but is difficult to maintain and reuse. - Internal CSS: Styles are placed inside a
<style>element in the document's<head>. It is suitable for styling a single page but cannot be shared efficiently across multiple pages. - External CSS: Styles are stored in a separate
.cssfile and linked using<link rel="stylesheet" href="styles.css">. It provides reusability, easier maintenance, browser caching, and consistent design across multiple pages.
External CSS is generally preferred for multi-page websites, while internal and inline CSS are useful for page-specific or element-specific requirements.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →