Using Floating Elements
In this lesson, we'll learn how to use floating elements in CSS. Let's begin!
We'll cover the following...
The browser renders the elements of an HTML page with a flowing layout. This means that it places the inline elements from left to right, and when it is necessary it starts a new line. Block elements are rendered from the top of the window down to the bottom.
You can change this behavior with the float property; setting its value left or right moves the related block element to the left or to the right, and the subsequent content wraps around the floating element.
The Listing below shows a simple web page that does not contain floating elements, it is displayed in the image that follows.
Listing: Using floating elements
<!DOCTYPE html> <html> <head> <title>Using floating elements</title> <style> body { font-family: Verdana, Arial, sans-serif; margin: 16px; } .image { width: 120px; height: 90px; margin-left: 8px; margin-bottom: 8px; border: 2px solid dimgray; background-color: lightgreen; /*float: right;*/ } .sidebar { width: 240px; margin-right: 8px; margin-bottom: 8px; border: 2px solid dimgray; background-color: lightskyblue; padding: 0 8px; /*float: left;*/ } .sidebar h2 { margin: 8px; } </style> </head> <body> <div class="image"></div> <aside class="sidebar"> <h2>Did you know?</h2> <p> HTML block elements can be set to float at the left or at the right edge of the page </p> </aside> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit fusce vel sapien elit in malesuada semper mi, id sollicitudin urna fermentum ut fusce varius nisl ac ipsum gravida vel pretium tellus tincidunt integer eu augue augue nunc elit dolor, luctus placerat scelerisque euismod, iaculis eu lacus nunc mi elit, vehicula ut laoreet ac, aliquam sit amet justo nunc tempor, metus vel. </p> </body> </html>
This page contains three block elements (<div>
, <aside>
, and <p>
), and by the standard rendering algorithm they are placed from top to bottom, each block element starting from the left.
Now, if you uncomment the float properties in the code listing, the layout of the page changes. The first empty box (<div>
) moves to the right, the “Did you know” sidebar (<aside>
) moves to the left, and the “Lorem ipsum” paragraph wraps around them, as shown below:
📜NOTE: ...