Master AI & Build your First Coding Portfolio with SkillReactor | Sign Up Now

Lesson 9 - Positioning And Layout

9.1 CSS Positioning

This chapter covers various CSS positioning techniques briefly.

  1. Static Positioning Static positioning is the default for all HTML elements. Elements are positioned according to the normal flow of the document.

    <style>
      #mydiv {
        position: static;
        /* Left, top, right, and bottom properties have no effect in static positioning */
        left: 10px; 
      }
    </style>
    <div>First Div</div>
    <div id="mydiv">Second Div</div>
    <div>Third Div</div>
    
  2. Relative Positioning Relative positioning allows you to move an element relative to its original position in the document flow. You can use the top, right, bottom, and left properties to adjust its position.

    <style>
      #mydiv {
        position: relative;
        top: 2px;
        left: 30px;
      }
    </style>
    <div>First Div</div>
    <div id="mydiv">Second Div</div>
    <div>Third Div</div>
    

    In this example, the #mydiv element is moved 20 pixels down and 30 pixels to the right from its normal position.

  3. Absolute Positioning Absolute positioning removes an element from the normal document flow and positions it relative to the nearest positioned ancestor (an element with position: relative, absolute, or fixed). If no such ancestor exists, it is positioned relative to the initial containing block (usually the <html> element).

    <style>
      #mydiv {
        position: absolute;
        top: 50px;
        left: 100px;
      }
    </style>
    <div>First Div</div>
    <div id="mydiv">Second Div</div>
    <div>Third Div</div>
    

    In this example, the #mydiv element is positioned 50 pixels from the top and 100 pixels from the left of its containing block.

  4. Fixed Positioning Fixed positioning removes an element from the normal document flow and positions it relative to the browser window. It remains in the same position even when the page is scrolled.

    <style>
      #mydiv {
        position: fixed;
        top: 0;
        right: 0;
      }
    </style>
    <div>This is a DIV element</div>
    

    In this example, the #mydiv element is positioned at the top-right corner of the browser window and remains there even when scrolling.