In the world of web design, sometimes we want to move an element to a specific location on the page, and it's very important to know how to use CSS tools for this task. The position
property in CSS is considered the most basic tool for changing the position of HTML elements on the page. There are several states that can be used for positioning elements anywhere you want.
We can all recall that using CSS features can help us with the position
property. This feature is used for controlling the positioning of elements on the page, and it can take states such as static
, relative
, absolute
, fixed
, and sticky
. Each of these states has its unique characteristics and behaviors that can affect the layout and positioning of elements to make it better for the web page design.
Now we want to delve deeper into these points, for example, when using the relative
state, an element moves relative to its original position, but extending the layout does not change. This type means that we can move an element locally for shifts. However, when we use absolute
, the element moves related to the nearest positioned ancestor without considering the surrounding page.
Don't forget to use fixed
which keeps an element in a specific position on the page even when scrolling. This is particularly useful for navigation elements or headers that should remain fixed. Another one of these states is sticky
, which is a combination of the concepts of static and relative. It means an element stays fixed until it reaches a specified point when the user scrolls to another point.
Usage Examples of the Position Feature in CSS
<style>
.relative-element {
position: relative;
top: 20px;
left: 30px;
}
.absolute-element {
position: absolute;
top: 50px;
left: 50px;
}
.fixed-element {
position: fixed;
bottom: 0;
width: 100%;
}
.sticky-element {
position: sticky;
top: 0;
}
</style>
<div class="relative-element">
This is a relative element.
</div>
<div class="absolute-element">
This is an absolute element.
</div>
<div class="fixed-element">
This is a fixed element.
</div>
<div class="sticky-element">
This is a sticky element.
</div>
Line-by-Line Code Explanation
position: relative;
This feature slightly changes the position of an element on the page relative to its original position.
top: 20px;
This means the element measures 20 pixels from the top.
left: 30px;
Moves the element 30 pixels to the right.
position: absolute;
Specifies the element's position relative to a specific position near its nearest positioned ancestor.
position: fixed;
The element is fixed outside the normal flow of the page and remains relative to the viewport.
position: sticky;
This causes an element to become static when it reaches a specific point from the page and then stays fixed thereafter.