3. A nested <div> example: Here we have placed a container (pink) inside another container (blue), which itself is inside a parent container (yellow). <head> <style type="text/css"> .yellow { width:400px; height:400px; background-color:yellow; } .blue { width:200px; height:200px; background-color:blue; } .pink { width:100px; height:100px; background-color:pink; } </style> </head> <div class="yellow"> <div class="blue"> <div class="pink"></div> </div> <!-- blue --> </div> <!-- yellow --> Notice the comments added to the last two closing </div> tags. These can help us later, especially when there is a lot of code between the opening and closing tags.
4.
5. Floating <div> elements: When we float elements, subsequent content stays at the same horizontal level and uses whatever space remains. Once that space is used up, the content will "wrap" to the beginning of the next line. <head> <style type="text/css"> .first { width:100px; height:100px; background-color:blue; float:left; } .second { width:100px; height:100px; background-color:yellow; float:left; } </style> </head> <div class="first"></div> <div class="second"></div> More content.<br /> More content.<br /> More content.<br /> More content.<br /> More content.<br /> More content. More content. More content. More content. More content.
6. Floating right and left: We can also float elements to both the right and left sides of the page. The subsequent content will still behave the same way, filling whatever space remains untaken by the floated elements. <head> <style type="text/css"> .first { width:100px; height:100px; background-color:blue; float:left; } .second { width:100px; height:100px; background-color:yellow; float:right; } </style> </head> <div class="first"></div> <div class="second"></div> More content.<br /> More content.<br /> More content.<br /> More content.<br /> More content.<br /> More content. More content. More content. More content. More content. This is commonly done to create a web page with three columns. A navigation bar will be floated left, an information bar floated right, and the main content will reside in the middle of the page.
7. Clearing the float: If we want to force the next element to start below the floated elements, we can clear the float. <head> <style type="text/css"> .first { width:100px; height:100px; background-color:blue; float:left; } .second { width:100px; height:100px; background-color:yellow; float:right; } .clearfloat { clear:both; } </style> </head> <div class="first"></div> <div class="second"></div> <div class="clearfloat"></div> More content.<br /> . . . More content. More content. More content. More content. More content.