This page showcases typical examples of using the float property.
Using the float property makes it simple to align content boxes horizontally.
Example
* { box-sizing: border-box; } .box { float: left; width: 33.33%; /* three boxes (use 25% for four, and 50% for two, etc) */ padding: 50px; /* if you want space between the images */ } |
What is box-sizing? You can effortlessly arrange three floating boxes in a row. Nonetheless, if you introduce elements that increase the width of each box (such as padding or borders), the layout may break. The box-sizing property enables us to incorporate the padding and border within the box’s overall width (and height), ensuring that the padding remains contained within the box and prevents any layout disruptions. |
The grid layout of boxes can also serve to showcase images positioned next to each other.
Example
.img-container { |
In the previous example, you learned how to float boxes side by side with equal widths. However, achieving equal heights for floating boxes can be challenging. A workaround is to set a fixed height, as demonstrated in the example below:
Example
.box { height: 500px; } |
However, this approach lacks flexibility. It works well when you can ensure that the boxes will always contain a consistent amount of content. However, in many cases, the content varies. When viewed on a mobile phone, for example, the second box’s content might overflow outside of the box. This is where CSS3 Flexbox proves useful, as it can automatically adjust box lengths to match the longest one.
Example
Utilizing Flexbox for crafting adaptable boxes:
Tip: For further information on the Flexbox Layout Module, refer to our CSS Flexbox Chapter. |
Another application of float involves constructing a horizontal menu using a list of hyperlinks.
Example
Using the float property to design entire web layouts is also a common practice.
Example
.header, .footer { background-color: grey; color: white; padding: 15px; } .column { float: left; padding: 15px; } .clearfix::after { content: “”; clear: both; display: table; } .menu { width: 25%; } .content { width: 75%; } |
Property |
Description |
box-sizing |
Determines whether the width and height of an element should incorporate padding and borders, or exclude them. |
clear |
Specifies the behavior of an element adjacent to a floating element. |
float |
Specifies whether an element should float to the left, right, or remain in its natural position. |
overflow |
Specifies the behavior when content exceeds the boundaries of an element’s box. |
overflow-x |
Specifies the handling of content overflow along the left and right edges of the element’s content area. |
overflow-y |
Specifies the handling of content overflow along the top and bottom edges of the element’s content area. |