Float in CSS

The float CSS property places an element on the left or right side with respect to other elements, allowing text and inline elements to wrap around it. Floats remove the HTML element from the normal flow of the page. To understand more about CSS float property, we cover an example.

In the example, we float an image side-by-side of text as shown in the below image.

float example

You can view the full source code example at CodePen below:

https://codepen.io/taimoorsattar/pen/OJXMbRK 👆👆👆

The HTML structure for the code defined below:

<div class="wrapper">

  <div class="clearfix">
    <p>Text Here...</p>
    <img class="img-right"
         alt="image" />

  </div> <!-- /.clearfix -->
  <div class="clearfix">
    <img class="img-left"
         alt="image" />
    <p>Text Here...</p>

  </div><!-- /.clearfix -->

</div><!-- /.wrapper -->

The structure of CSS / HTML structure for the above example is shown as below:

└── .clearfix
	└── <p>
	└── <img> .img-right

	└── <p>
	└── <img> .img-left

.wrapper class is used to maintain 960px width and center the HTML element.

  max-width: 960px;
  margin: 0 auto;

To place the image right and left of the content, we need to style the HTML element with the class name of .img-right and .img-left.

  width: 40%;
  float: right;

  width: 40%;
  float: left;

The gap between image and text is controlled by the padding property of text. We set box-sizing property to every HTML element so the width of every HTML element stays intact.

Border Box

  box-sizing: border-box;

  display: inline-block;
  font-size: 18px;
  width: 60%;
  line-height: 110%;
  padding: 25px;

As described in the below image, the second’s image overlaps the area of the first content. We need to fix the floats so the next content starts after the first content ends.

float clearfix

To clear float in CSS, we will follow the below code:

.clearfix::after {
  content: "";
  clear: both;
  display: table;

Thanks for reading the post.

If you want to learn how to build a full-stack subscription website, please check out my course.

If you find this post useful, please share it on your social platform to reach out to more people.

Share this Blog