In CSS, what is the difference between static (default) positioning and relative positioning?
position: relative places an element relative to its current position without changing the layout around it, whereas position: absolute places an element relative to its parent's position and changing the layout around it.
Static positioning is the default. It defines the position of a given box essentially as an unpositioned element – it flows in the normal rendering sequence of the web page.
Absolutely positioned elements are positioned with respect to a containing block, which is the nearest postioned ancestor. If there is no positioned ancestor, the viewport will be the containing block. Elements with fixed positioning are fixed with respect to the viewport—the viewport is always their containing block.
Static positioning is the default positioning model for elements. They are displayed in the page where they rendered as part of normal HTML flow. Statically positioned elements don't obey left
, top
, right
and bottom
rules:
Relative positioning allows you to specify a specific offset (left
, top
etc) which is relative to the element's normal position in HTML flow. So if I have a textbox inside a div
I could apply relative positioning on the textbox to have it display at specific place relative to where it would normally be placed within the div
:
There is also absolute positioning - whereby you specify the exact location of the element relative to the entire document, or the next relatively positioned element further up the element tree:
And when a position: relative
is applied to a parent element in the hierarchy:
Note how our absolutely-position element is bound by the relatively-positioned element.
And lastly there is fixed. Fixed positioning restricts an element to a specific position in the viewport, which stays in place during scroll:
You may also observe the behaviour that fixed-positioned elements do not cause scroll because they are not considered to be bound by the viewport:
Whereas absolutely-positioned elements are still bound by the viewport and will cause scrolling:
..unless of course your parent element uses overflow: ?
to determine the behaviour of the scroll (if any).
With absolute positioning and fixed positioning, the elements are taken out of HTML flow.
You can see a simple overview here: W3School
Also, if I recall correctly, when declaring an element relative, it will by default stay in the same place as it otherwise should, but you gain the ability to absolutely position elements inside it relatively to this element, which I've found very useful in the past.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With