W03 Learning Activities: CSS Layouts – Float
Overview
The CSS float property should be used for specific purposes and not for general layout on a
page.
For example, floating related images to the left or right inside containers with paragraphs
or other article
content would be appropriate. The element is removed from the normal flow layout when floated.
Prepare
float: right;
margin: 20px;
CSS Float is a property that can be applied to elements to remove them from the normal flow of
the page and allow other elements to wrap around them. The float property can be applied to
block-level elements and inline elements. The float property can be set to left or
right to move the element to the left or right in the document flow. For example, this code block in
this paragraph is floated to the right and contains a shorthand margin declaration that applies a
margin on all sides of the element.
Content that follows floating elements
The clear property in CSS is used to control how elements behave around floating elements. When you
use the float property to move elements to the left or right side of their container, other elements
will wrap around them. The clear property allows you to stop this wrapping behavior and force an
element to come below any floating elements.
When using clear: left on an element, it will move below any floating elements that are positioned
on the left side, ensuring that no left-floating elements appear beside it on the left. Similarly,
clear: right makes the element come below any right-floating elements, and clear: both
will ensure that the element comes below all floating elements on either side.
Key points to remember:
- By default, the CSS float property is
none. There is no need to apply the float declaration unless you intend to float the element. - To avoid unexpected layout issues, using the
cleardeclaration to manage elements following a floated element as needed.
Activity Instructions
- Open the file named float.html in the week03 folder.
- Also, open the linked CSS file named float.css found in the styles subfolder.
- Which HTML element was the float applied?
Check Your Understanding
The float is applied to the
imgelement that was embedded inside thedivelement with the class ofcol1. - What would happen if you applied the
clear: both;property to thefooterselector in CSS? Try it!Check Your Understanding
The
footerelement content would move back to the normal flow in relation to the floatedimg.
Optional Resources
- CSS Float – MDN
- CSS clear property – MDN