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 inside containers with paragraph or other article content would be appropriate. The float property has been used for larger schemed layout purposes but should be replaced with modern, more robust CSS layout methods which will be presented later in the course.
"The float CSS property places an element on the left or right side of its container, allowing text and inline elements to wrap around it. The element is removed from the normal flow of the page, though still remaining a part of the flow (in contrast to absolute positioning)." - MDN
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.
- 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
clear
declaration to manage elements following a floated element as needed.
Activity Instructions
- In the MDN
article on CSS float, use the Try it editor to view the effect of applying a float to the
box with a
float: left;
and afloat:right;
. - In this example, ⚙️ CodePen: Float
Example to which HTML element was the float applied?
Adjust the rendered output screen to a smaller width to see the effect of the float on the
other content on the page.
Answer
The float was applied to the
img
element that was embedded inside thediv
element (with the class ofcol1
). The effect of the float on the other elements and text node on the page is that theimg
element is removed from the normal inline flow of the page and thep
andfooter
(which is outside of thediv
) content was moved to available space around the inlineimg
element. - In the same CodePen, what would happen if you applied the
clear: both;
property to thefooter
?Answer
The
footer
element content would move back to the normal flow in relation to the floatedimg
.
Optional Resources
- CSS Float - MDN
- CSS clear property - MDN