Learn how to wrap elements around each other using floats.
- [Instructor] A common way to lay out webpages before Flexbox and Grid was using floats. A float in CSS says the block elements should wrap around other elements instead of starting after the element. It was originally created to allow text to wrap around images. You see this in something like a newspaper or magazine where you want to take up all the available space on the paper. On a website, you would want to do the same if you have an image mixed in with text. This is what the page looks like without float. You have a paragraph, then the image starts right below it, then the next paragraph below the image.
To get the text to wrap around the image, you give the image a property of float with a value of left or right, so in the code here, I have a photo which has a class of photo, so that's how I'm going to style it, so photo, and then float colon left, save, and refresh, and now everything after that photo goes around it, taking up the available space to the right of it. The text comes right up to the edge of the photo so in this case, you might want to add a margin to the right and below the image.
So I'm gonna go back into the CSS on line 11, margin-right: 20 pixels, and margin-bottom: 20 pixels, save, and refresh. You get this so that the text is nicely going around the image. Sometimes, though, you want the text to stop floating before it gets to the bottom of the photo. For this, we use the property, clear, so going into the code, I'm going to start a new line of CSS.
The third paragraph has a class of p3, so I'm going to style that, and then do clear colon left, save, and refresh, so now the paragraph starts below the photo. You can clear: left or clear: right depending on which float the item it's wrapping around is using, or you can use the value, both, if you need to clear floating items on both sides for some reason. While floats work really well for their intended purpose of wrapping text around an image, they don't work quite as well for laying out a webpage.
However, there weren't a lot of great options before Flexbox and Grid came along, so there are a lot of older webpages out there that do use floats to lay out multiple columns, so that might look something like this, where the sidebars use float to go to the left and right side of the page, with the main content in the center. While you probably won't use this method to do the layout on a new webpage, you'll likely see it on existing webpages that you might be working on.
- What is responsive design?
- The responsive page structure
- Accessibility and responsive design
- Using media queries
- Designing with CSS Grid
- Designing with CSS Flexbox