Use floats for text wrapping
A float moves a box toward one side and allows inline content to wrap around it. Floats remain useful for an image embedded in prose. For a page's main columns, flex or grid usually expresses the layout more directly.
.story__image {
float: left;
width: 10rem;
margin: 0 1rem 0.75rem 0;
}
.story { display: flow-root; }
.after-story { clear: both; }Place the image before the paragraph in .story. Text wraps beside the image while sufficient space exists. flow-root makes the story establish a new block formatting context and contain its float. The following section can use clear if it must begin below preceding floats in the relevant context.
Why a parent can appear too short
A parent containing only floated children may not acquire the height you expect from normal-flow children. This can make its background or border appear collapsed. Establishing a suitable formatting context is often a clearer fix than setting a guessed fixed height.
The historical clearfix
.clearfix::after {
content: "";
display: table;
clear: both;
}The generated clearing element is a legacy containment technique. You will see it in older stylesheets. For new code, evaluate whether flow-root expresses the same need more clearly. Do not use overflow:hidden solely as a containment trick without considering that it may clip content.
Responsive adjustment
@media (max-width: 30rem) {
.story__image {
float: none;
width: 100%;
margin: 0 0 1rem;
}
}On narrow screens, a full-width image can be easier to read around than a tiny remaining text column. Give an HTML image meaningful alternative text when its content matters.
Practice
- Wrap a paragraph around a floated image.
- Remove flow-root and inspect the parent border.
- Add a following heading and use clear to place it below the float.
- Rebuild a two-column application layout with grid instead of floats and compare the intent of the CSS.