DEV Community

Cover image for Have one strange float in CSS
Phan Công Thắng
Phan Công Thắng

Posted on • Originally published at thangphan.xyz

Have one strange float in CSS

When we talk about float in CSS, we usually only think about two values left, right, and wrap it up. But is it all of float?

In this article, we're going to discover some cases of float property in CSS.

Float

The floated element breaks the normal flow, and it will be wrapped by the inline element or text. I think we are familiar with this concept.

Here's what I want to say:

Case 1

Add the floated element to an element which we can change display property.

<div class="parent">
  <div class="float">Floated element</div>
</div>
Enter fullscreen mode Exit fullscreen mode
.parent {
  display: block;
  /*flex, grid, inline-flex, inline-grid, table...*/
}

.float {
  float: left;
}
Enter fullscreen mode Exit fullscreen mode

And I realize that:

float doesn't work with grid, flex property.

Case 2

What happen if I add display to the floated element?

<div id="float">Floated element</div>
Enter fullscreen mode Exit fullscreen mode
#float {
  display: inline-flex;
  float: left;
}
Enter fullscreen mode Exit fullscreen mode

I'm going to use javascript to check whether the CSS property change or not:

window.getComputedStyle(document.getElementById('float')).display
// it returns flex
Enter fullscreen mode Exit fullscreen mode

As you can see the display property was changed from inline-flex to flex.

Float can change the display property in CSS.

Case3

What happen if I set the height for the floated element.

<div class="parent">
  <div class="float">Floated element</div>
</div>
Enter fullscreen mode Exit fullscreen mode
.parent {
  border: solid 1px black;
  /*
   float: left
  */
}

.float {
  float: left;
  height: 100px;
}
Enter fullscreen mode Exit fullscreen mode

It will overload the parent's height. But If I add float: left to the parent element, the parent element is as tall as its tallest floated children.

To ensure the parent element can cover its nested floated children, we can set it to the floated element.

Conclusion

It's only a simple property in CSS, but there is a ton of cases that we can discover. If you have another case about the floated element.
Please share it with me!

Top comments (0)