• sashi

CSS Position Property (Intermediate)

Updated: Jul 13, 2020


We will introduce four CSS position properties. These are static, relative, absolute, and fixed.






Static Position Property

Static is a default property. We position an element in the normal flow of the page.

With the static position property, the position values such as left, top, right, or bottom does not have any effect. A z-index value in the static property neither has any effect.


Note that although we used "position:static" in the 'HTML Code' below, we can omit this since the static position is a default property. Therefore, the example 1 and the example 2 below display the same effect:


HTML Code:


<style>
   div.first {  position: static; }
   div.second {  position: static;  left: 50px;}
</style>
<h1 style="color:blue">The Static Position Property</h1>
<div class="first">This is a first block</div>
<div class="second">This is a second block. It is positioned in normal flow.</div>

Example 1


<style>
   div.first { }
   div.second {}
</style>
<h1 style="color:blue">The Static Position Property</h1>
<div class="first">This is a first block</div>
<div class="second">This is a second block. It is positioned in normal flow.</div>

Example 2


Relative Position Property

We position an element relative to its normal position using the relative property. Setting the top, right, bottom, and left properties of a relatively-positioned element will cause it to be adjusted away from its normal position. Other content will not be adjusted by this change.


HTML Code:

<style>
   div.first {}
   div.second {position: relative;  left: 50px;}
</style>
<h1 style="color:blue">The Relative Position Property</h1>
<div class="first">This is a first block</div>
<div class="second">This is a second block. Its position is adjusted.</div>

Example 3


Absolute Position Property

We position an element relative to its parent element.

See the example below. Note: The parent element must have position:relative property!


HTML Code:

.parent {
  position: relative;   // <--- Do not forget this
  width: 50%;
  height: 200px;
  border:1px solid ;
}
#nested {
  position: absolute;
  top: 40px;
  left: 50px;
  font-size:24px;
  border:1px solid ;
}
</style>
<h2 style="color:blue">The Absolute Position Property</h2>
<div class="parent">
   <div id="nested">This is nested Div</div>
</div>

Example 4



Fixed Position Property

When you want to fix an element in a fixed position on the screen, you can use the fixed position property. Scroll the bar blow and see what happens.


HTML Code:

<style>
.fixed {
  position: fixed;
  background-color: coral;
  width: 100%;
  height: 20px;
  border:1px solid ;
}
</style>
...
<div class="fixed">
	You cannot get rid of me
</div>
<br>
<p>First</p>
<p>Second</p>
<p>Third</p>
<p>Fourth</p>
<p>Fifth</p>
<p>Six</p>
...

Example 5










5 views0 comments

Recent Posts

See All