back to all posts

CSS Crash Course for Beginners -7

by Nabendu Biswas / July 21st, 2020

#css #beginners #webdev
Series: CSS-Basics

Welcome to part-7 of the series. In this part we will learn positioning in CSS.

Positioning in CSS

There are six different value in the property position in CSS. They are -

  • Static

  • Relative

  • Absolute

  • Fixed

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.

index.htmlindex.html

After that let’s create some basic styles for the elements in our styles.css file.

styles.cssstyles.css

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.

Web-pageWeb-page

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.

position: absolute.position: absolute.

Now, the h1 will not be shown in the box.

h1h1

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 topAt 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.

position: relativeposition: relative

And now our h1 element containing CSS is moved 40px down from the border of the box.

CSSCSS

Now, by giving position: absolute to h2 also we can move it anywhere.

position: absoluteposition: absolute

Now, both our h1 and h2 are moved to different places.

Both h1 and h2Both 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.

buttonbutton

Now, add the code for fixed-button class in the styles.css. We are making it fixed, with 20px from the top.

fixed-buttonfixed-button

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 buttonSticky Fixed button

This completes part-7 of the series.

Nabendu Biswas