Categories
CSS Web development

CSS Position Property

The CSS position property defines the type of positioning method used for an element.

Demo1:

Syntax:

position: static|absolute|fixed|relative|sticky;

static (default) – elements render in the order, as they appear in the document flow (static positioned elements are not affected by the top, bottom, left, and right properties).

Example:

<!DOCTYPE html>
<html>
<head>
<style>
#parent-1 {
  position: static;
  border: 3px solid #2a9d8f;
  width: 300px;
  height: 100px;
}

#child-1 {
  position: absolute;
  border: 3px solid #e76f51;
  top: 60px;
  right: 60px;
}

</style>
</head>
<body>

<h4>position: static;</h4>

<div id="parent-1">Parent-1: position: static.
  <div id="child-1">Child-1: position: absolute, right: 60px, top: 60px</div>
</div>

</body>
</html>

Output:

CSS position: static;

absolute – the element is positioned relative to its first positioned (not static) ancestor element.

Example:

<!DOCTYPE html>
<html>
<head>
<style>
#parent-2 {
  position: absolute;
  border: 3px solid #2a9d8f;
  width: 300px;
  height: 100px;
}

#child-2 {
  position: absolute;
  border: 3px solid #e76f51;
  top: 60px;
  right: 60px;
}

</style>
</head>
<body>

<h4>position: absolute;</h4>

<div id="parent-2">Parent-1: position: absolute.
  <div id="child-2">Child-1: position: absolute, right: 60px, top: 60px</div>
</div>

</body>
</html>

Output:

CSS position: absolute;

fixed – the element is positioned relative to the browser window (is positioned relative to the viewport, which means it always stays in the same place even if the page is scrolled).

Example:

relative – the element is positioned relative to its normal position (setting the top, right, bottom, and left properties of a relatively-positioned element will cause it to be adjusted away from its normal position).

Example:

<!DOCTYPE html>
<html>
<head>
<style>
#parent-3 {
  position: relative;
  border: 3px solid #2a9d8f;
  width: 300px;
  height: 100px;
}

#child-3 {
  position: absolute;
  border: 3px solid #e76f51;
  top: 60px;
  right: 60px;
}

</style>
</head>
<body>

<h4>position: relative;</h4>

<div id="parent-3">Parent-1: position: absolute.
  <div id="child-3">Child-1: position: absolute, right: 60px, top: 60px</div>
</div>

</body>
</html>

Output:

CSS position: relative;

sticky – the element is positioned based on the user’s scroll position (a sticky element toggles between relative and fixed, depending on the scroll position. It is positioned relative until a given offset position is met in the viewport – then it “sticks” in place (like position:fixed)).

Example:

Enjoy coding!