Advanced Web Programming

CSS, Layout, Responsive Design and Bootstrap

PGCP-AC

CSS controls the presentation and layout of structured documents. Reliable CSS comes from understanding how the browser resolves competing declarations, calculates boxes, places elements and adapts a design when content or viewport dimensions change.

1. The cascade and the box model

CSS associates selectors with declarations. External stylesheets support consistent styling across pages; internal styles belong to a document; inline declarations belong to an element. The cascade considers origin, importance, layers, specificity and source order. Within ordinary author rules of equal precedence, a more specific selector wins and a later rule resolves a specificity tie. Inheritance passes selected properties, such as text color, from parent to child; not every property inherits.

An element's box consists of content, padding, border and margin. With content-box, the declared width covers content; with border-box, it includes padding and border. Margin remains outside either width. Block, inline and inline-block behavior determine ordinary flow. display: none removes an element from layout, whereas visibility: hidden normally retains its space. Absolute positioning uses a containing block; fixed positioning commonly uses the viewport.

2. Responsive composition

Flexbox arranges items along a main axis and a cross axis. Grid addresses rows and columns together. Relative units, flexible images, a viewport meta tag and media queries help pages adapt to different screen sizes. A breakpoint should respond to layout needs rather than a particular device model. Bootstrap supplies a responsive grid, utilities and reusable components. Its traditional grid divides a row into twelve columns. Components such as wells, panels and jumbotrons belong to older Bootstrap versions and should be read in that context.

* { box-sizing: border-box; }
.cards { display: grid; grid-template-columns: repeat(2, 1fr); gap: 1rem; }
@media (max-width: 40rem) {
  .cards { grid-template-columns: 1fr; }
}

In this example, the content switches from two columns to one at the breakpoint. The layout remains useful without assigning every card a fixed pixel width. Test long text, narrow screens, zoom, keyboard focus and validation messages; a page that works only with its initial sample content is not reliably responsive.

3. Grid and component vocabulary

A typical Bootstrap layout nests columns inside a row inside a container. Two half-width columns can occupy six units each in a twelve-unit row and stack at a smaller breakpoint. Exact class names depend on the Bootstrap version used in the exercise. A fluid container expands across available width; a constrained container supplies responsive maximum widths. Do not combine CSS and JavaScript files from unrelated Bootstrap major versions.

ComponentPurpose
AlertA visible status or feedback message
Badge or labelA small count or category marker
Progress barProgress toward a measurable completion point
PaginationNavigation through pages of results
List groupA consistently styled set of related items
Dropdown and collapseControls revealing optional content
Tabs and pillsNavigation among related content panels
NavbarSite or application navigation
Button groupRelated actions presented together

Tables, images, forms and typography also have framework styling. Themes change visual treatment, while templates supply a starting page structure. Older wells, panels and jumbotrons solve presentation tasks that may use different components in later versions.

4. Selectors and specificity

Selectors connect rules to elements. Type selectors match element names, class selectors match reusable categories, ID selectors match a document identifier and attribute selectors match the presence or value of an attribute.

button { font: inherit; }                 /* type */
.card { border: 1px solid #bbb; }         /* class */
#main-menu { list-style: none; }          /* ID */
input[required] { border-inline-start: .25rem solid #b00020; }
.toolbar > button:hover { background: #e8eef8; }

Specificity can be understood as weights for IDs, classes/attributes/pseudo-classes and types/pseudo-elements. Combinators do not add specificity. Before specificity is compared, the cascade has already considered relevance, origin, importance and cascade layers. When competing declarations have the same precedence and specificity, the later one wins.

Avoid solving every conflict with !important. It changes precedence and often creates a growing override problem. Prefer predictable layers, modest selectors, component classes and source organization.

5. Box-model calculation

Under the default content-box, declared width covers only content. For this rule:

.panel {
  box-sizing: content-box;
  width: 300px;
  padding: 20px;
  border: 5px solid;
  margin: 10px;
}

The border-box width is 300 + 40 + 10 = 350px; the outer occupied width including horizontal margins is 370px. Under border-box, a declared 300px includes content, padding and border, while margin remains outside. A common baseline is:

*, *::before, *::after { box-sizing: border-box; }

Vertical margins between block boxes may collapse in normal flow. Padding does not collapse. Overflow occurs when content cannot fit its box; hiding overflow can conceal keyboard focus or important text, so it is not a general repair for poor sizing.

6. Normal flow, display and positioning

Normal flow provides a robust default. Block boxes generally begin on a new line; inline boxes participate within text; inline-block boxes flow inline while accepting box dimensions. display: none removes an element and its box, while visibility: hidden generally preserves its layout space.

Positioning has distinct uses:

PositionBehavior
staticNormal default positioning
relativeRemains in flow and can be offset; can establish a containing block
absoluteRemoved from normal flow and positioned against a containing block
fixedUsually positioned relative to the viewport
stickyBehaves in flow until a scroll threshold is reached

An absolutely positioned badge often belongs inside a relatively positioned card. Without an intended containing block, it may align against an unexpected ancestor. z-index operates within stacking contexts; a huge value cannot necessarily escape the stacking context created by an ancestor.

7. Flexbox

Flexbox lays out items along a main axis and aligns them on a cross axis.

.toolbar {
  display: flex;
  align-items: center;
  justify-content: space-between;
  gap: .75rem;
  flex-wrap: wrap;
}

.toolbar__search { flex: 1 1 18rem; }

With flex-direction: row, the main axis is horizontal in the common writing mode. justify-content distributes space on the main axis and align-items aligns items on the cross axis. flex-grow, flex-shrink and flex-basis define how an item shares available or missing space. Use gap for consistent spacing rather than margins tied to a particular item order.

8. CSS Grid

Grid manages tracks in two dimensions:

.cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(min(100%, 16rem), 1fr));
  gap: 1rem;
}

This pattern creates as many usable columns as fit, never requiring a card to exceed the container on a narrow screen. Explicit tracks come from template declarations; implicit tracks are created when placement requires more rows or columns. fr distributes remaining space after fixed and intrinsic sizing contributions are considered.

Use Flexbox when the main concern is a row or column of items. Use Grid when row-and-column relationships matter. They work well together: Grid can place cards while Flexbox arranges content inside each card.

9. Responsive design principles

Responsive design combines a suitable viewport, flexible media, fluid sizing and conditional rules.

<meta name="viewport" content="width=device-width, initial-scale=1">
img { max-width: 100%; height: auto; }
.page { width: min(100% - 2rem, 70rem); margin-inline: auto; }

@media (min-width: 48rem) {
  .layout { display: grid; grid-template-columns: 16rem 1fr; gap: 2rem; }
}

This mobile-first rule starts with one-column behavior and enhances the layout when sufficient space exists. Choose a breakpoint where the content begins to look constrained, rather than targeting a named phone or tablet.

Relative units solve different problems. rem follows the root font size, em follows the relevant element font size, percentages depend on a containing dimension and viewport units depend on viewport dimensions. clamp() can place a preferred fluid value between minimum and maximum limits.

10. Responsive accessibility

A responsive page must survive more than viewport resizing. Test browser zoom, increased text size, long names, translated text, validation messages, keyboard navigation and reduced motion preferences. Do not remove focus outlines without providing an equally visible replacement. Ensure color contrast is adequate and do not communicate state by color alone.

Visual reordering with Grid or Flexbox does not necessarily change DOM or keyboard order. Keep source order meaningful. Touch targets require usable size and spacing. Horizontal scrolling may be reasonable for a wide data table, but whole-page horizontal scrolling usually indicates a layout defect.

11. Bootstrap layout

Bootstrap provides predefined CSS, a responsive grid, utilities and components. A conventional grid nests columns inside a row and a row inside a container:

<div class="container py-4">
  <div class="row g-4">
    <main class="col-12 col-lg-8">Main content</main>
    <aside class="col-12 col-lg-4">Related content</aside>
  </div>
</div>

Both columns occupy all 12 units on smaller widths. At the lg breakpoint they occupy eight and four units. A .container has responsive maximum widths; .container-fluid remains full width. Gutters provide space between columns.

Utilities handle focused concerns such as spacing, display, flex alignment, color and sizing. Components supply coordinated structure and styling. Use the documented markup and JavaScript for the installed major version. Older course material may mention wells, panels, labels and jumbotrons; modern versions use alternatives such as cards, badges and utility-built sections.

12. Framework trade-offs

Bootstrap speeds consistent interface construction but does not replace CSS knowledge. Excessive utility combinations can obscure intent, while overriding framework rules with highly specific selectors creates fragile code. Define a small design vocabulary, customize documented variables where appropriate and keep application-specific components separate from framework internals.

Only load interactive JavaScript when components need it. A visual component still requires correct semantics: an alert should communicate status appropriately, a progress bar needs a meaningful value and a dropdown must support keyboard and focus behavior supplied by the framework implementation.

13. Complete responsive composition

<main class="page">
  <header class="hero">
    <p class="eyebrow">Learning path</p>
    <h1>Advanced Web Programming</h1>
  </header>
  <section class="cards" aria-label="Available topics">
    <article class="card"><h2>HTML</h2><p>Structure and semantics.</p></article>
    <article class="card"><h2>CSS</h2><p>Layout and responsive design.</p></article>
    <article class="card"><h2>JavaScript</h2><p>Behavior and application logic.</p></article>
  </section>
</main>
:root { color-scheme: light dark; font-family: system-ui, sans-serif; }
body { margin: 0; line-height: 1.5; }
.page { width: min(100% - 2rem, 70rem); margin-inline: auto; }
.hero { padding-block: clamp(2rem, 8vw, 6rem); }
.cards { display: grid; grid-template-columns: repeat(auto-fit, minmax(min(100%, 16rem), 1fr)); gap: 1rem; }
.card { padding: 1rem; border: 1px solid currentColor; border-radius: .75rem; }
.card:focus-within { outline: .2rem solid Highlight; outline-offset: .2rem; }
@media (prefers-reduced-motion: reduce) { *, *::before, *::after { scroll-behavior: auto !important; } }

The example avoids fixed card widths, preserves semantic source order, scales spacing and acknowledges a user motion preference.

14. Practical considerations

  1. Margin is outside the border and is not included by border-box.
  2. Inheritance and the cascade are different mechanisms.
  3. Later source order resolves a tie only after other cascade criteria are equal.
  4. visibility: hidden generally keeps layout space; display: none does not.
  5. justify-content follows the main axis, which changes with flex-direction.
  6. Grid is two-dimensional; Flexbox is primarily one-dimensional.
  7. A viewport meta element is essential for expected mobile sizing.
  8. Breakpoints should respond to content, not a device brand.
  9. Bootstrap's traditional grid has 12 units, but exact APIs depend on version.
  10. Visual CSS reordering can disagree with focus and reading order.

Continue learning

Related notes

Put this topic into timed practice

Open mock tests when you want full-exam pacing, or keep drilling in practice mode.