Week 2: Demo

CSS Float



The float property is very commonly used in laying out content in a web page. This property allows content to float to one side or the other around a given HTML element. This will change the alignment and positioning of other HTML elements as well as text content. The default behavior for block elements like div is to stack vertically, like the example below:

Box
Box
Box
CSS:
.box{
    width: 200px;
    padding: 20px;
    font-size: 1.5em;
    text-align: center;
}
HTML:
<div class="box" style="background-color:red">Box</div>
<div class="box" style="background-color:green">Box</div>
<div class="box" style="background-color:blue">Box</div>

Adding a float:left to the class will allow each of the divs to float next to each other, the top most being the left most, and as they continue they will stack towards the right.

Float Box
Float Box
Float Box

CSS:
.box2{
    width: 200px;
    padding: 20px;
    font-size: 1.5em;
    text-align: center;
    float: left;
}
HTML:
<div class="box2" style="background-color:red">Float Box</div>
<div class="box2" style="background-color:green">Float Box</div>
<div class="box2" style="background-color:blue">Float Box</div>

This box can float left of the paragraph of text that comes after it in the HTML.
Any text that comes directly after an element that has been set to float:left is going to show up on the right side of it, aligned with the top of the element. In order to make material show up underneath HTML elements that have been set to float, you need to create an HTML element with a style of clear:both, which is a CSS property that causes any HTML elements following floating elements to ignore the float behavior.


Here's some text that has been included after a clear:both style has been applied.

This div is floating left.
This div is floating right.
You can have HTML elements that are set to float:left or float:right and the text content that follows them will end up showing up in between like we see here. If the text content is long enough, it will wrap underneath the floating elements using the alignment set in CSS (default being left aligned).

Resources