Skip to main content
April 1, 2026Dan Rodney/9 min read

Div Tags, ID Selectors, & Basic Page Formatting

Master HTML div tags and CSS fundamentals

Core Concepts in This Tutorial

Div Tag Structure

Learn to create block-level containers that stack vertically and group content sections for better organization.

CSS ID Selectors

Master unique identifiers for styling specific elements with the hash (#) selector syntax.

Layout Control

Implement width, padding, margins, and centering techniques for professional page layouts.

Topics Covered in This HTML & CSS Tutorial:

Master the fundamentals of web layout design: dividing content with div tags, implementing unique IDs, controlling element dimensions with width and max-width properties, applying CSS background colors, adding internal spacing with padding, centering content for professional layouts, creating CSS borders, and writing efficient code using CSS shorthand and DRY principles.

Exercise Preview

intro to divs

Exercise Overview

In this exercise, you'll gain precise control over page layout using the powerful div tag (short for division). By wrapping content in div containers, you create logical sections that can be styled independently with CSS—a fundamental skill that forms the backbone of modern web design. This approach enables you to build sophisticated, responsive layouts that adapt seamlessly across different screen sizes and devices.

Div Versus Span: Understanding Block vs. Inline Elements

Building on the previous exercise where we used span tags, here's the crucial distinction every web developer must understand:

  • Span tags are inline elements that flow naturally within text content, sitting side-by-side on the same line without breaking the text flow.
  • Div tags are block elements that create distinct content blocks, automatically stacking vertically and occupying the full available width by default.

This fundamental difference determines how browsers render your content and influences every layout decision you'll make as a developer.

  1. If you completed the previous exercise, index.html should still be open in your code editor, and you can proceed directly to the next section. If you closed the file, navigate to your News website folder and reopen index.html. We strongly recommend completing the foundational exercises (1C–2A) before tackling this advanced layout work, as they establish essential concepts you'll build upon here.

    Div vs Span Elements

    FeatureDiv TagsSpan Tags
    Display TypeBlock elementsInline elements
    Layout BehaviorStack verticallyFlow horizontally
    Use CasesPage sections, containersText styling, small portions
    Recommended: Use div tags for major content sections and layout containers

Starting Fresh: If You Haven't Completed Previous Exercises (1C–2A)

  1. Close any open files in your code editor to avoid confusion.
  2. Navigate to your News website folder and open index-ready-for-divs.html.
  3. Use File > Save As to save this file as index.html, replacing any existing version in your project folder.

Wrapping Content in a Div & Setting a Page Width

Now we'll implement a fundamental web design pattern: creating a content wrapper that provides consistent width control and improved readability across all device sizes.

  1. Preview your current file in a browser to establish a baseline for comparison. Experiment by dragging the browser window edge to resize it from narrow to wide. You'll notice the content stretches to fill the entire viewport width—acceptable for narrow screens, but problematic on wider displays where excessive line lengths severely impact readability. Research shows that optimal reading comfort occurs with line lengths between 45-75 characters.

    The <div> tag provides the solution by creating controllable content containers.

  2. Return to index.html in your code editor to implement the container structure.

  3. Create a wrapper div around all page content by adding the opening tag immediately after the body element:

    </head>
    <body>
       <div>
       <h1>
  4. Complete the wrapper by closing the div tag just before the closing body tag at the file's end:

    <p class="author">This report was inspired by, but not written by <a href="https://www.theonion.com" target="_blank">The Onion</a></p>
       </div>
    </body>
    </html>
  5. Professional developers consistently indent nested code for maintainability. While browsers ignore indentation, proper formatting significantly improves code readability and team collaboration. Indent all content between your opening and closing div tags now.

    Creating Your First Wrapper Div

    1

    Add Opening Div Tag

    Place the opening div tag just below the body tag to begin wrapping all page content

    2

    Close the Div Tag

    Add the closing div tag just above the closing body tag at the bottom of the file

    3

    Indent Content

    Indent all content between the div tags for better code readability and organization

Code Indentation Shortcuts for Efficiency

Master these essential keyboard shortcuts to format code quickly. Select the lines you want to modify, then use:

  • Tab to indent selected lines. Shift–Tab to reduce indentation.
  • Cmd–] (Mac) or Ctrl–] (Windows) to indent.
    Cmd–[ (Mac) or Ctrl–[ (Windows) to reduce indentation.

Most modern code editors also offer automatic formatting commands that can instantly organize entire files.

  • Since professional websites typically contain multiple divs for different content sections, we need a way to target this specific div with CSS. Add a unique identifier to distinguish it from future divs:

    <body>
       <div id="wrapper">
          <h1>

    This ID creates a unique hook for CSS styling. Remember: IDs must be unique within each HTML page (unlike classes, which can be applied to multiple elements), and they should use descriptive names without spaces or special characters.

  • Now we'll create the CSS rule to control this div's width. In your style section, add the following rule between the existing p and .author rules:

    p {

    Code Omitted To Save Space

    }
    #wrapper {
       width: 580px;
    }.author {

    Code Omitted To Save Space

    }

    The hash symbol (#) creates an ID selector, telling CSS to target the element with that specific ID. ID selectors have high specificity in CSS, making them powerful tools for precise styling control.

  • Save your file and test the changes.
  • Return to your browser and refresh the page. The content now flows within a controlled 580-pixel width, creating more readable line lengths.
  • Test the responsive behavior by resizing your browser window narrower than 580 pixels. You'll notice horizontal scrolling appears—functional but not ideal for mobile users who expect content to adapt to their screen size.
  • Return to your code editor to implement a more sophisticated solution.
  • Replace the fixed width with a flexible maximum width approach:

    #wrapper {
       max-width: 580px;
    }

    This modern CSS technique provides the best of both worlds: controlled width on large screens and flexible adaptation on smaller devices.

  • Save the file and test your improvement.
  • Return to the browser and refresh the page.
  • Test the new responsive behavior by resizing your browser window. The content now intelligently adapts: maintaining the 580-pixel maximum width on larger screens while fluidly resizing to fit smaller viewports without horizontal scrolling. This approach ensures optimal user experience across all devices—a critical consideration in today's mobile-first web environment.

  • Essential Keyboard Shortcuts

    Basic Indentation

    Use Tab to indent and Shift-Tab to unindent selected lines of code quickly.

    Advanced Shortcuts

    Mac users: Cmd-] to indent, Cmd-[ to unindent. Windows users: Ctrl-] to indent, Ctrl-[ to unindent.

    Adding a Background-Color for Visual Hierarchy

    Strategic use of background colors creates visual depth and helps establish clear content hierarchy—essential principles of modern web design.

    1. Return to index.html in your code editor.
    2. Create a subtle page background by adding a body rule at the top of your style section:

      <style>
         body {
            background-color: #bdb8ad;
         }
         h1 {
            font-family: Arial, Helvetica, sans-serif;
            font-size: 35px;
            color: #006b3a;
         }

      This neutral background color provides subtle contrast without overwhelming the content.

    3. Save the file.
    4. Refresh your browser to see the background color applied across the entire viewport, creating a foundation for the content area.
    5. Return to your code editor to enhance the content area's visual prominence.
    6. Add a contrasting background to the content wrapper to create visual separation:

      #wrapper {
         max-width: 580px;
         background-color: #ffffff;
      }

      This white background creates a clean "card" effect that makes content feel more contained and professional.

    7. Save the file.
    8. Refresh your browser to see the layered background effect. The white content area now stands out prominently against the neutral page background, creating clear visual hierarchy and improved focus on your content.

    Background Color Strategy

    Apply background colors to both the body and wrapper div to create visual depth. The body background shows around the content area while the wrapper background highlights the main content.

    Adding Padding Inside the Div for Optimal Readability

    Proper spacing is crucial for readability and professional appearance. Padding creates breathing room that prevents content from feeling cramped or overwhelming.

    1. The content currently sits too close to the container edges, creating a cramped appearance that hinders readability. Add internal spacing to your wrapper div:

      #wrapper {
         max-width: 580px;
         background-color: #ffffff;
         padding: 40px;
      }

      This padding value creates 40 pixels of internal space on all four sides (top, right, bottom, left), following the CSS box model principles that govern how browsers calculate element dimensions.

    2. Save the file.
    3. Refresh your browser to see the improved spacing. The content now has comfortable breathing room, significantly enhancing readability and creating a more polished, professional appearance.

    Padding Implementation

    40px
    pixels of padding applied to all four sides

    Centering Content in the Window for Professional Layout

    Centered layouts create visual balance and focus, guiding users' attention while maintaining professional aesthetics across different screen sizes.

    1. Implement automatic centering using CSS margins:

      #wrapper {
         max-width: 580px;
         background-color: #ffffff;
         padding: 40px;
         margin-left: auto;
         margin-right: auto;
      }

      Understanding the distinction: margin controls space outside an element (between elements), while padding controls space inside an element (between content and borders).

    2. Save the file.
    3. Refresh your browser to see the centered layout in action.

      The centering mechanism works through CSS's automatic margin calculation: when left and right margins are set to auto, the browser calculates equal spacing on both sides. Since your div has a defined maximum width smaller than its container (the body), the browser automatically centers it horizontally. This technique remains one of the most reliable centering methods in modern web development.

    Auto Margin Centering Technique

    Setting left and right margins to 'auto' automatically makes them equal, centering any element with a defined width within its container. This is the standard method for horizontal centering in CSS.

    Margin vs Padding

    FeatureMarginPadding
    LocationOutside the elementInside the element
    AffectsSpace between elementsSpace within element borders
    Background ColorDoes not showShows element background
    Recommended: Use margin for spacing between elements, padding for internal spacing

    Adding a Border for Definition

    Subtle borders provide visual structure and help define content areas without overwhelming the design—a hallmark of sophisticated web interfaces.

    1. Add border properties to create subtle definition around your content area:

      #wrapper {
         max-width: 580px;
         background-color: #ffffff;
         padding: 40px;
         margin-left: auto;
         margin-right: auto;
         border-width: 3px;
         border-style: solid;
         border-color: #959485;
      }

      The border-style property determines how browsers render the border. Common values include solid (continuous line), dashed (broken line segments), dotted (series of dots), and none (invisible border).

    2. Save the file.
    3. Refresh your browser to see the refined 3-pixel solid border that adds subtle definition without overpowering the content. The carefully chosen color complements the overall design palette while providing gentle visual boundaries.

    Border Specifications

    3px
    pixel border width applied

    Border Style Options

    Solid

    Creates a continuous unbroken line around the element. Most commonly used for clean, professional designs.

    Dashed

    Produces a series of short dashes. Useful for creating subtle separations or indicating optional sections.

    Dotted

    Creates a series of dots around the border. Good for decorative purposes or informal designs.

    CSS Optimization: Mastering Shorthand & DRY Principles

    Professional developers write efficient, maintainable code by eliminating redundancy and using CSS shorthand properties. This approach improves performance, reduces file size, and makes code easier to maintain.

    1. Return to index.html in your code editor to optimize your CSS.

    2. Replace the three separate border declarations with CSS shorthand syntax:

      #wrapper {
         max-width: 580px;
         background-color: #ffffff;
         padding: 40px;
         margin-left: auto;
         margin-right: auto;
         border: 3px solid #959485;
      }

      CSS shorthand properties combine multiple related properties into single declarations. The border shorthand follows the pattern: width, style, color. This approach reduces code length while maintaining identical functionality.

    3. Now apply the fundamental DRY principle ("Don't Repeat Yourself") to eliminate redundant font-family declarations throughout your CSS.

      Currently, you're declaring font-family: Arial, Helvetica, sans-serif; multiple times across different elements. Professional developers consolidate such repetitions by leveraging CSS inheritance—child elements automatically inherit certain properties from their parents.

      Since all page elements sit inside the body tag, declaring the font-family once in the body rule allows all nested elements to inherit this property automatically.

    4. Refactor your CSS rules to eliminate redundancy:

      body {
         font-family: Arial, Helvetica, sans-serif;
         background-color: #bdb8ad;
      }
      h1 {
         font-size: 35px;
         color: #006b3a;
      }
      h2 {
         font-size: 24px;
         color: #8f6800;
      }

      Remove the redundant font-family declarations from the h1 and h2 rules, relying instead on inheritance from the body element.

    5. Save the file.
    6. Refresh your browser to confirm the visual output remains identical. Your code is now more maintainable, efficient, and follows professional development standards. These optimization techniques become increasingly valuable as projects scale and teams collaborate on larger codebases.

    Key Takeaways

    1Div tags are block-level elements that stack vertically, perfect for creating page sections and layout containers
    2ID selectors use the hash (#) symbol and can only be applied to one element per page, making them highly specific
    3Setting max-width instead of width creates flexible layouts that adapt to different screen sizes
    4The combination of margin-left: auto and margin-right: auto centers elements horizontally within their container
    5CSS shorthand properties like 'border: 3px solid #color' are more efficient than multiple separate declarations
    6The DRY principle encourages moving common properties to parent elements to reduce code repetition
    7Proper code indentation using keyboard shortcuts improves readability and maintainability
    8Understanding the difference between margin (outside spacing) and padding (inside spacing) is crucial for layout control

    RELATED ARTICLES