• Post category:CSS

Floating elements in CSS | Step by Step Guide

Floating Elements in CSS

Learn floating elements in CSS with simple steps:

CSS “float” property is used to move HTML elements to our desired location. We can assign the value “left” and “right” to this property. If we give the float value left to the child element in HTML only the child element is floated on the left side. That is if you give a float value left to a parent element, all the child elements inside the parent element will float on the left side. So, You should use the float property carefully. Take a look at the example code below to get an in-depth concept of how works float property.

How to float an Element

Follow these two easy steps to float an HTML element easily:

1. Create any HTML Element

Here we have created three child div inside a parent div. Then we have given the classname red, green, and blue to those three child divs. And for those three child divs, we have set background-color red, green, and blue separately and we also set bg-color to parent div. By default, these div elements have 100% width because they are block-level elements. So, we set the width of all child divs to 100px. See the below output, three boxes are created.

HTML :

<div class="wrap">
<div class="blue box"></div>
<div class="red box"></div>
<div class="green box"></div>
</div>

CSS:

.blue{
background: blue; }

.red{
background: red; }

.green{
background: green; }

.box{
height: 100px;
width:100px; }

.wrap{
background-color: silver;
padding: 20px; }

Expected output:

 floating elements in css

2. Use CSS float property

Now, if you want to float right in the blue box. You need to set the CSS “float” property to “right”. See the below output, the blue box is floated on the right side.

.blue{
background: blue;
float:right; }

Output:

READ ALSO  Which Property is Used to Change the Font of an Element?

 floating elements in css

If you set the CSS “float” property to “right” to a red child div, your red box will float on the right side.

.red{
background: red;
float:right; }

Output:

 floating elements in css

Conclusion

So, you need to use the CSS “float” property to float an element to the left or right side.

I hope you find this guide useful and keep learning to code!

Leave a Reply