back to all posts

CSS Crash Course for Beginners -6

by Nabendu Biswas / July 20th, 2020

#css #beginners #webdev
Series: CSS-Basics

Welcome to part-6 of the series. We will learn about Alignment and Floating in this part. They are a bit of old concept, but still in use at a lot of places.

Alignment and Floating

Head over to your index.html file from the previous part and add three blocks of div, with each containing a h2 and a p tag.

index.htmlindex.html

It will show three blocks like below on our web-page. In this normal flow, we will have them one after the other.

Web-pageWeb-page

Now, we want all these three blocks appears in a vertical fashion and occupying 33.3% space each. We will do this by the float: left property, which floats an element to the left.

So, head over to the styles.css and add the below styles.

float: leftfloat: left

Now, all the blocks will occupy the 33.3% of the page.

All elements floatingAll elements floating

As you might have seen from above, that the <hr> after the block div was missing. This happens because when we float something, it messes with tags after it. The way to fix it is to use an empty div with any class name after the floating element. We generally name the class clearfix.

clearfixclearfix

After that in our styles.css use the property clear:both to fix our float issue.

clear: bothclear: both

It will solve our issue and the horizontal rule will be shown again.

hr againhr again

Next, we will see how to create a two column layout using float. For this create two sections with id — *main__block and side__bar

Two sectionsTwo sections

After this we just have to give one property of float: left and the other float: right, which the required width.

The StylesThe Styles

Now, our two column layout is perfect.

Two Column layoutTwo Column layout

But what if we want to add some padding and border to both. Let’s add the same in our CSS.

border and padding.border and padding.

It will mess up things in our web-page. It is because by default in css, everything is a content-box which is defined by the box-sizing property. It mean any element like a div, will take it’s width plus the border and the padding.

Things messed upThings messed up

We are going to solve this issue by making the box-sizing: border-box in both of our elements. It includes the border and the padding to the div’s width.

A very good reference to understand both can be find here.

box-sizingbox-sizing

It solves our issue and the layout again looks good.

PerfectPerfect

This completes part-6 of the series.

Nabendu Biswas