HtmlCssMonk

Positions in CSS | Learn Basic CSS

DESCRIPTION

CSS helps us to position our HTML element. We can put any HTML element at whatever location we like.

Position property can have 7 values –

ValueDescription
staticDefault value. Elements render in order, as they appear in the document flow
absoluteThe element is positioned relative to its first positioned (not static) ancestor element
fixedThe element is positioned relative to the browser window
relativeThe element is positioned relative to its normal position, so “left:20px” adds 20 pixels to the element’s LEFT position
stickyThe element is positioned based on the user’s scroll position
A sticky element toggles between relative and fixed, depending on the scroll position.
initialSets this property to its default value. 
inheritInherits this property from its parent element.

Relative Positioning

In relative positioning , the element is positioned according to the normal flow of the document, and then offset relative to itself based on the values of top , right, bottom and left. The offset does not affect the position of any other elements.

EXAMPLE –

<html>

<head>
</head>

<body>
  <div style="position:relative; left:60px; top:30px; background-color:aqua;">
    This div has relative positioning.
  </div>
</body>

</html>

This Code will produce the following result on your webpage –


Absolute Positioning

In absolute positioning , the element is removed from the normal document flow, and no space is created for the element in the page layout. It is positioned relative to its closest positioned ancestor, if any; otherwise, it is placed relative to the initial containing block. Its final position is determined by the values of top , right, bottom and left.

EXAMPLE –

<html>
   <head>
   </head>

   <body>
      <div style = "position:absolute; left:70px; top:30px; background-color:aqua;">
         This div has absolute positioning.
      </div>
   </body>

</html> 

This Code will produce the following result on your webpage –


Fixed Positioning

In fixed positioning , the element is removed from the normal document flow, and no space is created for the element in the page layout. It is positioned relative to the initial containing block established by the viewport . Its final position is determined by the values of top , right, bottom and left.

EXAMPLE –

<html>

<head>
</head>

<body>
  <div style="position:fixed; left:60px; top:30px; background-color:aqua;">
    This div has fixed positioning.
  </div>
</body>

</html>

This Code will produce the following result on your webpage –


Next topic – Introduction to JavaScript

Previous topic – Background in CSS


Leave a Comment

Your email address will not be published. Required fields are marked *