Learn HTML
Lesson 1 - Overview Of The Web And HTML
Lesson 2 - HTML Tags And Elements
Lesson 3 - Images And Multimedia
Lesson 4 - Writing Your First HTML Page
Lesson 5 - Overview Of CSS
Lesson 6 - CSS Selectors And Properties
Lesson 7 - Applying CSS To HTML
Lesson 8 - Box Model
Lesson 10 - Flexbox
This chapter covers various CSS positioning techniques briefly.
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>
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.
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.
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.