In this tutorial, we will explore the different types of CSS positioning: static, relative, absolute, sticky; and float properties: left, right, none. Understanding these concepts is crucial for creating well-structured and visually appealing web pages.
CSS Positioning
Static Positioning
The default value for the position property in CSS is static
. Elements are positioned according to the normal flow of the page. They are not affected by top, bottom, left or right properties.
div {
position: static;
}
Relative Positioning
An element with position: relative;
is positioned relative to its normal position. Setting the top, right, bottom and left properties will cause it to be adjusted away from its normal position.
div {
position: relative;
top: 20px;
}
Absolute Positioning
An element with position: absolute;
is positioned relative to the nearest positioned ancestor (instead of positioned relative to the viewport). If no such ancestor exists, it uses document body as reference.
div {
position: absolute;
top: 80px;
}
Sticky Positioning
An element with position: sticky;
, behaves like a relatively positioned element until it crosses a specified point then it behaves like a fixed position element thereafter.
div {
position: sticky;
top: 0;
}
CSS Float
Float Left
An element with float: left;
will move as far to the left as possible and allows text and inline elements to wrap around it.
div {
float: left;
}
Float Right
An element with float: right;
will move as far to the right as possible. Text and inline elements will wrap around it on the left side.
div {
float: right;
}
No Float
The float: none;
property is used for cancelling any floats currently applied on an element.
div {
float: none;
}
In conclusion, understanding how CSS positioning and floating works can help you create more complex layouts. Practice using these properties in your projects to get a better grasp of them.