Skip to main content
April 2, 2026Dan Rodney/8 min read

CSS Styling for Optimal Web Layout

Master CSS Layout Techniques for Professional Web Design

Course Continuation

This exercise builds on Exercise 3b of the Revolution Travel website. If you haven't completed the previous exercise, ready-to-use starter files are provided to help you jump in at this point.

HTML Structure Elements

Header & Navigation

Contains the main site branding and navigation menu. These elements are styled differently from the main content area.

Main Content Area

Houses the primary page content including H1, H2, and H3 headings. Currently too wide and needs CSS constraints.

Footer Section

Bottom page content that should align with the main content width for visual consistency.

Embedded CSS vs External CSS

Pros
Good for single-page projects and quick prototyping
Essential knowledge for HTML email development
No external file dependencies
Easier to understand when learning CSS basics
Cons
Cannot be shared across multiple pages
Makes HTML files larger and harder to maintain
Less efficient for multi-page websites
Violates separation of concerns principle

Width Units: Pixels vs Percentages

FeatureFixed PixelsPercentage Width
ResponsivenessStatic across all screensAdapts to screen size
ControlPrecise pixel controlRelative to container
Mobile FriendlyMay overflow on small screensScales with device
Best Use CaseFixed layouts, precise designResponsive fluid layouts
Recommended: Use percentages with max-width constraints for optimal responsive design

Creating Responsive Width with Max-Width

1

Set Percentage Width

Start with 90% width to create flexible sizing that adapts to different screen sizes while maintaining margins

2

Add Max-Width Constraint

Set max-width to 800px to prevent content from becoming too wide on large screens

3

Center with Auto Margins

Use margin-left: auto and margin-right: auto to center the content horizontally on the page

DRY Principle in CSS

Don't Repeat Yourself - Use comma-separated selectors like 'main, footer' to apply the same styles to multiple elements, reducing code duplication and making maintenance easier.

Images come in at their native size by default. If they're small, they're small. If they're big, they're big, and they are a fixed size.
Understanding why images don't automatically scale and need CSS rules for responsive behavior
Essential Image Rule

Always include 'img { max-width: 100%; }' in your CSS. This prevents images from overflowing their containers and is fundamental for responsive design.

Responsive Design Concepts

Fluid Layout

Uses flexible units like percentages that change based on screen size. Creates adaptable designs that work across devices.

Responsive Web Design

Involves media queries and breakpoints to create different layouts for different screen sizes. More advanced than fluid design.

Mobile Optimized

Design approach that ensures websites work well on mobile devices through flexible layouts and appropriate sizing.

Font Weight Values

100 - Thin
100
400 - Normal
400
700 - Bold
700
900 - Heavy
900

Typography Hierarchy Setup

1

Set Base Font Family

Apply sans-serif font family to the body element to establish the base typography for the entire page

2

Style All Headings

Use grouped selectors (h1, h2, h3) to apply consistent color and remove default bold styling

3

Define Individual Sizes

Set specific font sizes for each heading level: H1 at 28px, H2 at 23px, maintaining visual hierarchy

Default vs Custom Paragraph Spacing

FeatureBrowser DefaultCustom Styling
Font Size16px16px (kept)
Line HeightDefault spacingIncreased for readability
Bottom Margin16px22px
Recommended: Custom spacing improves readability and visual flow between paragraphs
Margin Collapse Behavior

When two elements with margins are adjacent, the margins collapse to the larger of the two values rather than adding together. This prevents excessive spacing between elements.

This lesson is a preview from our Web Development with HTML & CSS Course Online (includes software) and Full-Stack Web Development Certificate Online (includes software). Enroll in a course for detailed lessons, live instructor support, and project-based training.

We're continuing our work on the Revolution Travel website project. If you're joining this exercise fresh or need to catch up, you'll find starter files available in the sidebar. However, if you completed exercise 3b successfully, continue using your existing Revolution Travel folder—there's no need to start over.

For those reviewing specific techniques or jumping into this particular lesson, the provided starter folders will get you up to speed quickly. Here's our current progress: we've established the fundamental page structure with semantic HTML5 elements.

Our page now features a proper document outline: a header containing our branding, a navigation section, the main content area, and a footer. To visualize this structure in action, open your browser's Developer Tools by right-clicking and selecting "Inspect." You'll see our semantic markup clearly: the header at the top, followed by the nav element, the substantial main content section, and finally the footer anchoring the bottom of the page.

Within the main content area, we've implemented a logical heading hierarchy. Our primary topic uses an H1 tag, while major sections like "Things to Do" and "Travel Tips" utilize H2 headings. Individual attractions—Fisherman's Wharf, Alcatraz Island, and others—are marked up with H3 tags, creating a clear information architecture that benefits both users and search engines.

Now we need to address a critical usability issue: our content spans the entire viewport width, creating an uncomfortable reading experience. Research consistently shows that optimal reading requires constraining line length—typically 45-75 characters per line for maximum comprehension and user engagement.

We'll solve this with CSS. While we could create an external stylesheet to serve the entire website (and we'll explore that approach in upcoming exercises), we're embedding CSS directly in this page for now. This technique proves invaluable in certain scenarios—HTML email development, for instance, requires embedded styles since linked stylesheets aren't supported across email clients. Understanding embedded CSS gives you flexibility when external linking isn't viable.

Let's create our style block. I'll add a style tag here, and notice how our context shifts: while the tag itself is HTML, everything inside follows CSS syntax rules. We're no longer creating elements—we're styling the elements we've already established.

Our header and navigation elements need different treatment—they'll be centered and don't require width constraints. However, our main content and footer need consistent sizing and alignment. Rather than writing separate rules for each element, we'll follow the DRY principle (Don't Repeat Yourself) and create a single rule targeting both elements simultaneously.

Using CSS selector grouping, we can style multiple elements with one declaration: `main, footer`. The comma creates a selector list, applying identical styles to both the main content area and footer. This approach keeps our code maintainable and reduces redundancy.

For width control, we have several approaches. A fixed pixel value like 900px creates consistency but lacks responsiveness—it might overflow smaller screens or appear cramped on larger displays. Let's start with a percentage-based approach: 70% of the parent container width.

Since both elements sit within the body tag, they'll occupy 70% of the viewport width. However, this creates an alignment issue—all our whitespace appears on the right side. We need to center our content column by distributing the remaining 30% equally between left and right margins.

The solution: `margin-left: auto` and `margin-right: auto`. These declarations tell the browser to automatically calculate equal margins on both sides, effectively centering our content. Here's a VS Code productivity tip: you can copy entire lines without highlighting by simply placing your cursor anywhere on the line and using Ctrl+C (or Cmd+C), then Ctrl+V (or Cmd+V) to duplicate.


Our 70% width works reasonably well on smaller screens, providing adequate breathing room without wasting space. As screens get larger, the proportion maintains good readability. Let's adjust to 90% for better utilization of available space on mobile devices—this strikes a better balance between content and whitespace.

However, on very large displays, 90% becomes problematic—lines grow too long for comfortable reading. We need an upper boundary using max-width. By setting `max-width: 800px`, we tell the browser: "Use 90% of the available width, but never exceed 800 pixels." This creates a responsive layout that adapts to small and medium screens while maintaining optimal readability on larger displays.

Now let's address our images. Unlike text, images don't automatically reflow—they render at their native dimensions regardless of container size. This behavior stems from the web's origins when fixed desktop screens were the norm. Before smartphones and tablets created the multi-device landscape we navigate today, web developers could assume consistent screen sizes.

Modern web development requires responsive design—layouts that adapt gracefully across devices and screen sizes. While true responsive design involves media queries (which we'll cover later), we're currently implementing a fluid layout that provides excellent cross-device compatibility through flexible sizing.

To make images fluid, we need a universal rule: `img { max-width: 100%; }`. This declaration prevents images from exceeding their container's width while maintaining aspect ratios. Whether images sit within the main tag, article elements, or any other container, they'll scale appropriately without breaking your layout.

This image rule should be standard practice for every website you build in 2026. Browser defaults can't change because doing so would break existing websites—backward compatibility is sacred on the web. Therefore, developers must explicitly override defaults to achieve modern responsive behavior.

Our layout is becoming more sophisticated and user-friendly. Next, let's address typography. The current serif font doesn't match our brand aesthetic—sans-serif fonts typically provide better screen readability and convey a more modern, approachable feeling appropriate for a travel website.

By applying `font-family: sans-serif` to the body element, we leverage CSS inheritance—all child elements will adopt this font choice unless specifically overridden. The browser will select Arial as the primary choice, Helvetica as a fallback, and finally any available sans-serif font as a last resort. This font stack ensures consistent appearance across different operating systems and devices.

For our headings, we want visual consistency and brand alignment. Rather than writing separate rules for H1, H2, and H3 elements, we'll group them: `h1, h2, h3`. This allows us to apply shared properties—like our brand orange color—while maintaining the flexibility to customize individual heading levels as needed.

The color we're implementing—that distinctive orange—creates visual cohesion with our logo and reinforces brand identity throughout the page. We're also removing the default bold weight with `font-weight: normal`. Just because browsers apply default styling doesn't mean we're constrained by it—CSS gives us complete control over visual presentation.

Font weights use numerical values from 100 (ultra-thin) to 900 (ultra-bold), with keyword equivalents: normal (400) and bold (700). This system provides subtle typographic control that enhances visual hierarchy and brand expression.


While our headings share color and weight properties, they need distinct sizing to establish clear information hierarchy. Our H1 gets 28px for primary topics, H2 receives 23px for major sections, and H3 will use 18px for subsections. In professional workflows, these specifications typically come from design systems created in tools like Figma, ensuring consistency between design and development teams.

Line height significantly impacts readability, especially when text wraps across multiple lines. Our H1 needs a line height of 36px—this creates comfortable vertical spacing that improves scanning and comprehension. The relationship between font size and line height is crucial for optimal typography.

Paragraph spacing requires careful attention to the CSS box model. By default, paragraphs receive 16px margin above and below—equal to the default font size. We can verify this using Developer Tools: right-click any paragraph, select "Inspect," and examine the computed styles panel.

Our design calls for increased paragraph spacing to improve content flow and readability. We'll implement `line-height: 1.6` for comfortable within-paragraph spacing and `margin-bottom: 22px` for better separation between paragraphs—an increase from the 16px default that creates more breathing room in our content.

Understanding margin collapse is crucial for precise spacing control. When two block-level elements sit vertically adjacent, their margins don't add together—instead, the larger margin value wins. If one paragraph has 40px bottom margin and the next has 10px top margin, the total space between them is 40px, not 50px. The smaller margin "collapses" into the larger one.

This behavior only affects vertical margins—horizontal margins always add together as expected. It's an important consideration when calculating total spacing in your layouts, and understanding it prevents confusion when your spacing calculations don't match visual results.

Our major page sections—header, nav, main, and footer—need better separation to establish clear visual boundaries. By applying `margin-bottom: 30px` to all four elements simultaneously, we create consistent spacing throughout the page structure while maintaining DRY principles.

To complete our header design, let's add a subtle border that serves as a visual separator: `border-bottom: 1px solid #ccc`. The color value #ccc represents a light gray—when all digits in a hex color are identical, you're looking at a grayscale value. Numbers create darker grays, letters create lighter ones.

This border needs internal spacing to separate it from our logo. Unlike margin (which creates external space), padding creates internal space within an element's boundaries. We'll add `padding-top: 20px` and `padding-bottom: 15px` to give our header proper breathing room while maintaining the border's visual effectiveness as a section divider.

These foundational styling techniques create a professional, responsive layout that works beautifully across devices while maintaining excellent readability and brand consistency. As we continue building this site, these principles will scale effectively across all pages and components.

Key Takeaways

1Embedded CSS is useful for single-page projects and essential for HTML email development, though external CSS is better for multi-page websites
2Use percentage widths with max-width constraints to create responsive layouts that work on both small and large screens
3The DRY principle applies to CSS - use comma-separated selectors to avoid repeating styles for similar elements
4Always include max-width 100% for images to prevent overflow and ensure responsive behavior across devices
5Fluid layouts use flexible units and adapt to screen size, while responsive design involves media queries for different breakpoints
6Browser defaults can be overridden with CSS - headings are bold by default but can be changed to normal font weight
7Typography hierarchy requires both consistent styling across heading levels and individual font size specifications
8Margin collapse means adjacent element margins use the larger value rather than adding together, preventing excessive spacing

RELATED ARTICLES