CSS for Web Development

0% completed

Previous
Next
How float works

Float is a CSS property that allows you to take an element out of the normal flow and move it to the left or right side of its container. When an element is floated, other content wraps around it. This property is useful for creating multi-column layouts and aligning images with text.

Floating an element changes how the other elements are arranged. The floated element still remains a part of the document but no longer takes up space in the normal flow, so text and inline elements wrap around it.

Syntax

Follow the code block below to set the float property in CSS:

/* Float an element to the left */ float: left; /* Float an element to the right */ float: right; /* Remove floating (default behavior) */ float: none;

Explanation:

  • float: left;
    • Moves the element to the left side of its container, with subsequent content wrapping around it on the right.
  • float: right;
    • Moves the element to the right side of its container, with subsequent content wrapping around it on the left.
  • float: none;
    • Ensures the element does not float and remains in the normal document flow.

Example 1: Floating an Image to the Left

In this example, we float an image to the left of a paragraph of text. The text flows around the image, creating a classic layout for content with an image.

HTML

. . . .

Explanation:

  • Float Property:
    • The class .float-left applies float: left to the image.
  • Margin:
    • A margin of 15px on the right and bottom provides spacing between the image and the text.
  • Outcome:
    • The image is aligned to the left, and the paragraph wraps around the right side, creating a cohesive and visually appealing layout.

Example 2: Floating an Element to the Right

In this example, we float a block element (a <div>) to the right within its container. This demonstrates how the content behaves when an element is aligned to the right.

HTML

. . . .

Explanation:

  • Float Property:
    • The class .float-right applies float: right, aligning the <div> to the right.
  • Margins:
    • Margins on the left and bottom provide space between the floated element and the text.
  • Outcome:
    • The text in the .text-content container wraps around the floated element, demonstrating how floating elements affect content flow.

This lesson demonstrates how the float property works by moving elements to the left or right and allowing other content to wrap around them. Understanding float is a key step in building flexible and dynamic web layouts.

.....

.....

.....

Like the course? Get enrolled and start learning!
Previous
Next