Welcome to part-7 of the series. In this part we will learn positioning in CSS.
There are six different value in the property position in CSS. They are -
We will learn about them in a practical way now. Let’s start by adding a h1 and h2 tag, wrapped in a div in our index.html file.
After that let’s create some basic styles for the elements in our styles.css file.
It will now show as below in our web-page. One thing to note is that every element by default is position: static, so the h1 and h3 will follow it’s natural order.
We will now see position: absolute. If we use it in any element, we can move it with top, left, right and bottom properties. Let’s give position: absolute to the h1 and use top property to move it 40px from top.
Now, the h1 will not be shown in the box.
It will be shown at the top of the page. It is because the position absolute, by default takes the whole page as it’s parent. So, it moves the h1 from the top of the page to 40px.
At the top
Now, we don’t want to move it from the top of the page. But we want it to move within the box.
To fix the issue, we have to make the parent element position: relative. So, we will add this property in position-box.
And now our h1 element containing CSS is moved 40px down from the border of the box.
Now, by giving position: absolute to h2 also we can move it anywhere.
Now, both our h1 and h2 are moved to different places.
Both h1 and h2
Now, we will learn about another position property and that is fixed. For that first create a new button and give it two classes button and fixed-button.
Now, add the code for fixed-button class in the styles.css. We are making it fixed, with 20px from the top.
By doing so, we made the button sticky. It will always remain 20px from the top, even when we scroll the page. This is used very frequently in creating sticky navbars or social media buttons, to keep them always be shown.
Sticky Fixed button
This completes part-7 of the series.