CSS Position Property

CSS Position Property

As web developer, we probably interact with the css everday. But when code for HTML layout, sometimes it’s still headache for many programmers. So this post is aim to provide a better understanding about how to use CSS Position property when building HTML layout.

As we all know, HTML layout is based on Documentation Flow model. In this model, block element hold in a line and inline element opposite. Below it’s an example to show the difference between each other.

Block & Inline

1
2
<div style = "border: 1px solid">Block One</div>
<div style = "border: 1px solid">Block Two</div>

alt text

1
2
<a href="#" style = "border: 1px solid">Inline Element One</a>
<a href="#" style = "border: 1px solid">Inline Element Two</a>

alt text

1
2
3
4
<div style = "border: 1px solid">Block One</div>
<div style = "border: 1px solid">Block Two</div>
<a href="#" style="border: 1px solid">Inline Element One</a>
<a href="#" style="border: 1px solid">Inline Element Two</a>

alt text

Position Property

In CSS, Position property is used to indicate one element position inside HTML. The syntax as below:

1
2
3
position: static;
position: relative;
position: absolute;

  • Position: static

The default position for all HTML element is static if not set yet.

1
<div style = "border: 1px solid">Block One</div> <!-- 'position: static' add to style automatically-->

  • Position: relative

The relative is used to indicate the element position based on the previous position. Here the element is still in the documentation flow, which means the previous position is still hold space.

1
2
3
4
5
6
7
8
9
10
11
.divStyle {
width:100px; height:100px;
border: 1px solid
}
#One {
position:relative; // Set to relative
left:150px; // Move to right 150px
}
<div class = "divStyle" id = "One">Block One</div>
<div class = "divStyle" id = "Two">Block Two</div>

alt text

  • Position: absolute

Compare with relative, absolute is used to indicate the element in a specified position relative to its closest ancestor if any, or otherwise relative to the initial containing block. Here the element is out of documentation flow, which means the previous position is no existing anymore. In the example it will be replaced by blobck two.

1
2
3
4
5
6
7
8
9
10
11
.divStyle {
width:100px; height:100px;
border: 1px solid
}
#One {
position:absolute; // Set to absolute
left:150px; // Move to right 150px
}
<div class = "divStyle" id = "One">Block One</div>
<div class = "divStyle" id = "Two">Block Two</div>

alt text