CSS Tutorial - CSS Float








float property creates floating boxes, which are shifted to one side until the left or right edge touches the edge of the containing block or another floating box.

The possible value for float is :left or right or none.

  • left - shift element so that the left edge touches the left edge of the containing block or the right edge of another floating block.
  • right - shift element so that the right edge touches the right edge of the containing block or the left edge of another floating block.
  • none - The element is not floated.

The following code shows the float property.


<!DOCTYPE HTML>
<html>
<head>
<style>
p.toggle {<!--from  w w w  . j  a v a 2s.  c  om-->
  float: left;
  border: medium double black;
  width: 40%;
  margin: 2px;
  padding: 2px;
}
</style>
</head>
<body>
  <p class="toggle">This is a test.</p>
  <p class="toggle">This is a test.</p>
  <p>This is a test.</p>
  <p>
    <button>Left</button>
    <button>Right</button>
    <button>None</button>
  </p>
  <script>
    var buttons = document.getElementsByTagName("BUTTON");
    for (var i = 0; i < buttons.length; i++) {
      buttons[i].onclick = function(e) {
        var elements = document.getElementsByClassName("toggle");
        for (var j = 0; j < elements.length; j++) {
          elements[j].style.cssFloat = e.target.innerHTML;
        }
      };
    }
  </script>
</body>
</html>

The code above is rendered as follows:





Clear

By default, floating elements will stack up next to one another.

The clear property clears the stacking up.

It specifies that one or both edges of a floating element must not adjoin the edge of another floating element.

Its possible values are:

  • left - The left edge of the element may not adjoin another floating element.
  • right - The right edge of the element may not adjoin another floating element.
  • both - Neither edge may adjoin another floating element.
  • none - The element is not cleared and either edge may adjoin another floating element.

The following code shows the clear property in use.


<!DOCTYPE HTML>
<html>
<head>
<style>
p.toggle {<!-- w  w  w  . j a va  2s. c o  m-->
  float: left;
  border: medium double black;
  width: 40%;
  margin: 2px;
  padding: 2px;
}
p.cleared {
  clear: left;
}
</style>
</head>
<body>
  <p class="toggle">This is a test.</p>
  <p class="toggle  cleared">This is a test.</p>
  <p>This is a test.</p>
  <p>
    <button>Left</button>
    <button>Right</button>
    <button>None</button>
  </p>
  <script>
    var buttons = document.getElementsByTagName("BUTTON");
    for (var i = 0; i < buttons.length; i++) {
      buttons[i].onclick = function(e) {
        var elements = document.getElementsByClassName("toggle");
        for (var j = 0; j < elements.length; j++) {
          elements[j].style.cssFloat = e.target.innerHTML;
        }
      };
    }
  </script>
</body>
</html>

The code above is rendered as follows: