Be the first user to complete this post
|Add to List|
OverviewTo design and understand the page layouts, we need to understand the position property in css. An element is said to be positioned, when its position attribute is set.
The default value for the position attribute is static.
position : relative || absolute || fixed || sticky (experimental);
This post is one of the posts in the series of posts to understand the position attribute in css. Make sure to read all of them to fully understand the position attribute.
- position : static || relative - element is in the normal document flow.
- position : absolute || fixed - element is absolutely positioned.
- float : left || right - element is floating. Learn More about floats.
Getting startedIf we do not apply any position to the squares then they are rendered in the normal document flow, meaning the green square is rendered to the next available space after the red square. In the below pen, we have three colored square div elements, which have the default (static) position. Hence, they are rendered in the normal document flow. [codepen_embed height="268" theme_id="0" slug_hash="bErjVW" default_tab="result" user="kavitshah8"]See the Pen relative-1 by Kavit Shah (@kavitshah8) on CodePen.[/codepen_embed]
If will apply, the position: relative to the red square, then it will be a positioned element. It will allow us to offset the element. The below pen offsets the red square from top by 30px and left by 70px; [codepen_embed height="268" theme_id="0" slug_hash="OMjwmp" default_tab="result" user="kavitshah8"]See the Pen relative-2 by Kavit Shah (@kavitshah8) on CodePen.[/codepen_embed]
Notes on offset
- Positive offset value moves an element away from the edge, applying 'left: 20px' moves an element 20px away from the edge towards right and vice versa.
- Offset does not remove an element from its normal document flow, which is very different than the floated element.
- In the above example, offsetting the red square did not remove it from its original place. Hence, the green square could not occupy its position.
- But if we increase the dimensions of the red square then we can see the position of the green square changes as shown in the below pen.
Check out James Williamson's excellent tutorial on Relative Positioning !
Most common use cases for
- To tweak the layouts. For example, to offset an element.
- It's also used to apply position to container elements which allows us to apply position: absolute to the child elements.
- css - circular profile pictures
- Making max width work in internet explorer
- nodejs: generate uuid / guid
- Getting started with automation testing for webrtc applications
- Applying floats to inline elements
- Testing promise sequence using mocha, chai, chai-as-promised, sinon
- querySelector vs getElementById