Static, Relative, Absolute, and Fixed: What's the Difference?
Though the fundamental concept of 'HTML (Content) + CSS (Presentation) = Webpages seems simple at a high-level, when you actually experiment and delve into the intricacies of both HTML and CSS, you quickly realize the criticality of understanding the 'Why' of things. For example, when trying to space an image on the page, sometimes I haphazardly fuddle through adding margins and paddings -almost in a trial-and-error process - until I'm feeling satisfied or too frustrated, whichever comes first.
The same issue applies for positioning elements, and as this is a fundamental and critical aspect of web design, I feel it's worth the time to take a look under the hood and really understand what is going on. This will hopefully save you some time, mental agony, and allow you to better put into fruition your creativity!
There are four main positioning attributes in CSS:
- Static Positioning:
- Is the default position for all elements.
- Displays elements as you would expect them to appear - in a standard one-after-another order.
- Is typically not used unless you're overriding another positioning declaration, but this shouldn't happen much since positioning doesn't cascade.
- Relative Positioning:
- Basically means, "Relative to Itself." You can use attributes, top, left, bottom, and right to define how many pixels the element should move off of from the specified side.
- Ex: top: 50px takes 50px from the top, and basically pushes the element down
- Doesn’t affect other static elements; static elements wont adjust to an element’s relative positions so overlap is possible.
- Use z-index for layering order of overlapping elements (default: 1, set z-index to a higher number to bring to front)
- Limits the scope of Absolutely positioned child elements (Absolute positioning explained below)
- Child elements will be kept within the parent element. If Parent is left Static, child elements will position themselves to the browser.
- Absolute Positioning:
- 'Removes' the element from the document and places it according to the declared top, bottom, left, and right attributes.
- Elements using absolute are removed from the DOM, thus static elements will move up to fill the space the absolute element was.
- Is determined by its parent elements
- If there are no parent elements or they are static, elements are positioned based on
- Fixed Positioning:
- Puts elements relative to the viewport, or browser window.
- Holds elements in their position even when the page is scrolled.
Check out the simulator at the bottom of this page for practice!
Resources: