Photo by JESHOOTS.COM on Unsplash
How Many types of Positioning are there in CSS(Cascading style sheet);
Positioning are there in CSS
Sure, I'd be happy to explain the types of positioning in CSS.
- Static Positioning: This is the default positioning of an HTML element. The element follows the normal document flow and is positioned according to its place in the HTML code. Static positioned elements cannot be moved using top, left, right or bottom properties.
CSS code snippet:
div {
position: static;
}
- Relative Positioning: Relative positioning moves an HTML element relative to its original position without affecting the other elements on the page. When you use the top, bottom, left, and right properties with relative positioning, it sets these values relative to the element's initial position.
CSS code snippet:
div {
position: relative;
top: 20px;
left: 30px;
}
- Absolute Positioning: Absolutely positioned HTML elements are positioned relative to their nearest positioned ancestor (i.e, an ancestor element with any positioning value other than static) instead of the document's containing block. If there is no positioned ancestor, the element is positioned relative to the initial containing block (usually the document body). Absolutel positioned elements do not take up space in the document flow, which means that other elements will fill the gap left by the positioned element.
CSS code snippet:
div {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
- Fixed Positioning: Fixed positioning is similar to absolute positioning, except that it positions elements relative to the viewport, not to the containing block. Fixed positioned elements do not move when the page is scrolled. When using fixed positioning, you would typically set the top and right/left properties to create a "sticky" element, like a navigation menu.
CSS code snippet:
div {
position: fixed;
top: 0;
right: 0;
}
I hope that helps you understand the different positioning types in CSS!