In this tutorial, our goal is to master CSS positioning. We will delve into the four main types of positioning: static, relative, absolute, and fixed. Understanding how these work will allow you to control where and how elements are displayed on your pages.
By the end of this tutorial, you will be able to:
- Understand the differences between static, relative, absolute, and fixed positioning
- Apply these positioning concepts to your CSS code
- Manipulate the layout of your webpage using positioning
This tutorial assumes basic knowledge of HTML and CSS. If you're new to these, you may want to get familiar with them first.
This is the default positioning for HTML elements. They are positioned according to the normal flow of the page, left to right and top to bottom.
An element with relative positioning is positioned relative to its normal position. The 'top', 'right', 'bottom', and 'left' properties can be used to move the element from its normal position.
An absolute positioned element is positioned relative to the nearest positioned ancestor. It is taken out of the normal flow of the page and no space is created for the element in the page layout.
A fixed positioned element is positioned relative to the browser window. Even if the page is scrolled, the element will stay in the same place.
div {
position: static;
}
This is the default, so this code doesn't change the position of the div.
div {
position: relative;
top: 20px;
left: 20px;
}
This code will move the div 20px down and 20px to the right from its normal position.
div {
position: absolute;
top: 30px;
right: 10px;
}
This code positions the div 30px from the top and 10px from the right of its nearest positioned ancestor.
div {
position: fixed;
bottom: 0;
right: 0;
}
This div will always be positioned at the bottom right corner of the window, even when scrolling.
In this tutorial, we learned about the four types of CSS positioning: static, relative, absolute, and fixed. We also saw how they impact the layout of a webpage.
For your next steps, experiment with these different positioning styles on your own projects. Try combining them and see how they interact with each other.
You can also explore the CSS z-index
property, which works in tandem with positioning to control the stack order of elements.
Solutions are available, but try to solve it on your own first. Remember, practice makes perfect. Happy coding!