Hướng dẫn và ví dụ CSS Float và Clear

1- CSS float

CSS {float: left | right | inline-start | inline-end} làm một phần tử nổi (float) ở bên cạnh trái hoặc cạnh phải của phần tử chứa nó. Nó cho phép các nội dung văn bản và các nội dung nội tuyến (inline content) bao quanh nó.

Syntax


/* Keyword values */
float: left;
float: right;
float: none;
float: inline-start;
float: inline-end;

/* Global values */
float: inherit;
float: initial;
float: unset;
 


CSS {float: left}

Làm cho phần tử nổi (float) ở bên cạnh trái của phần tử chứa nó.

CSS {float: right}

Làm cho phần tử nổi (float) ở bên cạnh phải của phần tử chứa nó.

CSS {float: inline-start}

  • CSS {float: inline-start} hoạt động giống với CSS {float: left} nếu phần tử cha có chiều từ trái sang phải (Left to Right – LTR)
  • CSS {float: inline-start} hoạt động giống với CSS {float: right} nếu phần tử cha có chiều từ phải sang trái (Right to Left – RTL)

CSS {float: inline-end}

  • CSS {float: inline-end} hoạt động giống với CSS {float: right} nếu phần tử cha có chiều từ trái sang phải (Left to Right – LTR)
  • CSS {float: inline-end} hoạt động giống với CSS {float: left} nếu phần tử cha có chiều từ phải sang trái (Right to Left – RTL)

CSS {float: none}

Loại bỏ trạng thái nổi (float) của phần tử.

Ví dụ với CSS {float: left | right}:

float-example.html


<!DOCTYPE html>
<html>
   <head>
      <title>CSS float</title>
      <meta charset="UTF-8"/>
      <style>
          .container {
            background-color: #eee;
            min-height: 135px;
            padding: 5px;
            text-align: left;
          }
          .container span {
            background-color: yellow;
          }
          #myElement {
            background-color: lightgreen;
            color: red;
            font-weight: bold;
            width: 180px;
            height: 50px;
            padding: 5px;
            margin: 5px;
          }
      </style>
      <script>
          function changeFloat(event)  {
             var floatValue = event.target.value;
             var myElement = document.getElementById("myElement");
             myElement.style.float = floatValue;
             myElement.innerHTML = "{float: "+ floatValue+"}";
          }
      </script>
   </head>
   <body>
       <h1>CSS float</h1> 
       <input type="radio" name="my-radio" value="none" onclick="changeFloat(event)" checked/> None<br>
       <input type="radio" name="my-radio" value="left" onclick="changeFloat(event)"/> Left<br>
       <input type="radio" name="my-radio" value="right" onclick="changeFloat(event)"/> Right
       <hr/>
       <div class = "container">
             <div id = "myElement">
                {float: none} (Default)
             </div>
             Apollo 11 was the spaceflight that landed the first humans,
             Americans <span>Neil Armstrong</span> and <span>Buzz Aldrin</span>,
             on the Moon on July 20, 1969, at 20:18 UTC.
             <span>Armstrong</span> became the first to step onto the lunar
             surface 6 hours later on July 21 at 02:56 UTC.

             <span>Armstrong</span> spent about three and a half two
             and a half hours outside the spacecraft,
             <span>Aldrin</span> slightly less; and together they
             collected 47.5 pounds (21.5 kg) of lunar material
             for return to Earth. A third member of the mission,...
       </div>
   </body>
</html>

Nếu bạn áp dụng CSS {float: left | right | inline-start | inline-end} cho một phần tử nội tuyến (inline element), trình duyệt sẽ tự động biến phần tử này thành phần tử khối (block element). Cụ thể CSS {display:inline} sẽ biến thành CSS {display:block}. Nó cũng có thể biến đổi các giá trị khác của CSS display.

Original value
Computed value

{display:inline}
{display:block}

{display:inline-block}
{display:block}

{display:inline-table}

{display:table}

{display:table-row}
{display:block}

{display:table-row-group}
{display:block}

{display:table-column}
{display:block}

{display:table-column-group}
{display:block}

{display:table-cell}
{display:block}

{display:table-caption}
{display:block}

{display:table-header-group}
{display:block}

{display:table-footer-group}
{display:block}

{display:inline-flex}

{display:flex}

{display:inline-grid}

{display:grid}

other

unchanged

Dưới đây là một ví dụ, phần tử nội tuyến <span> sẽ được đối xử như một phần tử khối khi bạn áp dụng CSS {float: left | right | inline-start | inline-end} cho nó.

float-example2.html


<!DOCTYPE html>
<html>
   <head>
      <title>CSS float</title>
      <meta charset="UTF-8"/>
      <style>
         .container {
           background-color: #eee;
           min-height: 135px;
           padding: 5px;
           text-align: left;
         }
         .container span {
           background-color: yellow;
         }
         #myElement {
           background-color: lightgreen;
           color: red;
           font-weight: bold;
           width: 180px;
           height: 50px;
           padding: 5px;
           margin: 5px;
         }
      </style>
      <script>
         function changeFloat(event)  {
            var floatValue = event.target.value;
            var myElement = document.getElementById("myElement");
            myElement.style.float = floatValue;
         }
      </script>
   </head>
   <body>
      <h1>CSS float with Inline Element</h1>
      <input type="radio" name="my-radio" value="none" onclick="changeFloat(event)" checked/> None<br>
      <input type="radio" name="my-radio" value="left" onclick="changeFloat(event)"/> Left<br>
      <input type="radio" name="my-radio" value="right" onclick="changeFloat(event)"/> Right
      <hr/>
      <div class = "container">
         <span id = "myElement">
           I am a Span Element.
           {width: 180px; height: 50px;}
         </span>

         Apollo 11 was the spaceflight that landed the first humans,
         Americans <span>Neil Armstrong</span> and <span>Buzz Aldrin</span>,
         on the Moon on July 20, 1969, at 20:18 UTC.
         <span>Armstrong</span> became the first to step onto the lunar
         surface 6 hours later on July 21 at 02:56 UTC.
         <span>Armstrong</span> spent about three and a half two
         and a half hours outside the spacecraft,
         <span>Aldrin</span> slightly less; and together they
         collected 47.5 pounds (21.5 kg) of lunar material
         for return to Earth. A third member of the mission,...
      </div>
   </body>
</html>

2- Ví dụ với CSS float

Khi một phần tử được thả nổi (floated), nó sẽ thoát ra khỏi quy tắc bố trí thông thường của tài liệu. Nó sẽ bị dịch chuyển sang trái (Hoặc sang phải) cho tới khi chạm vào cạnh của phần tử cha, hoặc chạm vào phần tử nổi (floating element) khác.

float-example3.html


<!DOCTYPE html>
<html>
   <head>
      <title>CSS float</title>
      <meta charset="UTF-8"/>
      <style>
         .container {
           background-color: #eee;
           min-height: 135px;
           padding: 5px;
         }
         .container span {
           background-color: yellow;
         }
         .float-left {
           background-color: lightgreen;
           float: left;
           width: 70px;
           height: 50px;
           padding: 5px;
           margin: 5px;
         }
         .float-right {
           background-color: lightblue;
           float: right;
           width: 100px;
           height: 70px;
           padding: 5px;
           margin: 5px;
         }
      </style>
   </head>
   <body>
      <h1>CSS float</h1>
      <div class = "container">
         Apollo 11 was the spaceflight that landed the first humans,
         Americans <span>Neil Armstrong</span> and <span>Buzz Aldrin</span>,
         on the Moon on July 20, 1969, at 20:18 UTC.
         <div class = "float-left">
              Float left
         </div>
         <div class = "float-right">
              Float right
         </div>
         <div class = "float-left">
              Float left
         </div>
         <span>Armstrong</span> became the first to step onto the lunar
         surface 6 hours later on July 21 at 02:56 UTC.
         <span>Armstrong</span> spent about three and a half two
         and a half hours outside the spacecraft,
         <span>Aldrin</span> slightly less; and together they
         collected 47.5 pounds (21.5 kg) of lunar material
         for return to Earth. A third member of the mission,...
      </div>
   </body>
</html>

Ví dụ ảnh (image) với CSS float:

img-float-example.html


<!DOCTYPE html>
<html>
   <head>
      <title>CSS float Image</title>
      <meta charset="UTF-8"/>
      <style>
         .container {
           background-color: #eee;
           min-height: 135px;
           padding: 5px;
         }
         .img-left {
           float: left;
           margin: 5px;
         }
      </style>
   </head>
   <body>
      <h1>CSS float Image</h1>
      <div class = "container">
         Apollo 11 was the spaceflight that landed the first humans,
         Americans Neil Armstrong and Buzz Aldrin,
         on the Moon on July 20, 1969, at 20:18 UTC.
         <img src="../images/flower.png" class = "img-left"/>

         Armstrong became the first to step onto the lunar
         surface 6 hours later on July 21 at 02:56 UTC.
         Armstrong spent about three and a half two
         and a half hours outside the spacecraft,
         Aldrin slightly less; and together they
         collected 47.5 pounds (21.5 kg) of lunar material
         for return to Earth. A third member of the mission,...
      </div>
   </body>
</html>

3- CSS Clear

CSS {clear: left | right} được áp dụng cho một phần tử để không cho phép một phần tử khác nổi (float) bên trái hoặc bên phải của nó. CSS clear chỉ hoạt động nếu thỏa mãn các điều kiện sau:

  1. Trong code, phần tử hiện tại (<current-element>) phải được viết sau phần tử nổi (<floating-element>).
  2. Phần tử hiện tại phải là một phần tử nổi (floating element) hoặc là một phần tử khối (block element).

<floating-element>
<current-element>

Chú ý: Nếu CSS {clear: left | right} hoạt động, nó sẽ đẩy phần tử hiện tại xuống dòng tiếp theo.

Syntax


/* Keyword values */
clear: none;
clear: left;
clear: right;
clear: both;
clear: inline-start;
clear: inline-end;

/* Global values */
clear: inherit;
clear: initial;
clear: unset;
 


CSS {clear: inline-start}

  • CSS {clear: inline-start} hoạt động giống với CSS {clear: left} nếu phần tử cha có chiều từ trái sang phải (Left to Right – LTR)
  • CSS {clear: inline-start} hoạt động giống với CSS {clear: right} nếu phần tử cha có chiều từ phải sang trái (Right to Left – RTL)

CSS {clear: inline-end}

  • CSS {float: clear-end} hoạt động giống với CSS {clear: right} nếu phần tử cha có chiều từ trái sang phải (Left to Right – LTR)
  • CSS {clear: inline-end} hoạt động giống với CSS {clear: left} nếu phần tử cha có chiều từ phải sang trái (Right to Left – RTL)

CSS {clear: both}

CSS {clear: both} = {clear: left} + {clear: right}.

CSS {clear: none}

Loại bỏ CSS Clear ra khỏi phần tử.

4- CSS Clear cho phần tử nổi

CSS {clear: left | right} có thể áp dụng cho một phần tử nổi (floating element) – {float: left | right | inline-start | inline-end | both}, để ngăn chặn một phần tử nào đó nổi bên trái hoặc bên phải nó.


<floating-element>
<current-element>

Dưới đây là các hình minh họa các tình huống có thể xẩy ra:

Hai phần tử cùng nổi trái – {float:left}. Áp dụng CSS {clear: left} cho phần tử thứ hai sẽ đẩy nó xuống dòng tiếp theo, để đảm bảo rằng phần tử thứ nhất không còn nổi bên trái nó.

Phần tử hiện tại nổi phải – {float:right}, còn phần tử kia nổi trái – {float:left}. Áp dụng CSS {clear: left} cho phần tử hiện tại sẽ đẩy nó xuống dòng tiếp theo, để đảm bảo rằng phần tử kia không còn nổi bên trái nó.

Phần tử hiện tại nổi trái – {float:left}, còn phần tử kia nổi phải – {float:right}. Áp dụng CSS {clear: right} cho phần tử hiện tại sẽ đẩy nó xuống dòng tiếp theo, để đảm bảo rằng phần tử kia không còn nổi bên phải nó.

Hai phần tử cùng nổi phải – {float:right}. Áp dụng CSS {clear: right} cho phần tử hiện tại sẽ đẩy nó xuống dòng tiếp theo, để đảm bảo rằng phần tử kia không còn nổi bên phải nó.

Ví dụ:

clear-example1.html


<!DOCTYPE html>
<html>
   <head>
      <title>CSS Clear</title>
      <meta charset="UTF-8"/>
      <link rel="stylesheet" href="clear-example1.css" />
      <script src="clear-example1.js"> </script>
   </head>
   <body>
       <h1>CSS Clear</h1>
       <div class="option">
         #floating-element <br/><br/>
         <input type="radio" name="f-radio" value="left" onclick="changeFloat1(event)" checked/> float:left <br/>
         <input type="radio" name="f-radio" value="right" onclick="changeFloat1(event)"/> float:right
       </div>
       <div class="option">
         #current-element <br/><br/>
         <input type="radio" name="c1-radio" value="left" onclick="changeFloat2(event)" checked/> float:left <br/>
         <input type="radio" name="c1-radio" value="right" onclick="changeFloat2(event)"/> float:right
       </div>
       <div class="option">
         #current-element <br/><br/>
         <input type="radio" name="c2-radio" value="none" onclick="changeClear2(event)" checked/> clear:none <br/>
         <input type="radio" name="c2-radio" value="left" onclick="changeClear2(event)"/> clear:left <br/>
         <input type="radio" name="c2-radio" value="right" onclick="changeClear2(event)"/> clear:right
       </div> 
       <hr/>
       <p style="color:blue;">
          CASE: #current-element is a Floating Element.
       </p>
       <div class = "container">
            <div id = "floating-element">
              FLOATING-ELEMENT <br/>
              {float: left}
            </div>
            <div id = "current-element">
              CURRENT-ELEMENT <br/>
              {float: left}
            </div>
       </div>
   </body>
</html>

clear-example1.css


.option {
  display: inline-block;
  width: 130px;
  margin-right: 5px;
  padding: 5px;
  border: 1px solid black;
}
.container {
  background-color: #eee;
  padding: 15px;
  height: 200px;
}
.container div {
   margin: 5px;
   padding:10px;
}
#current-element {
    float: left;
    width: 170px;
    height: 100px;
    background: yellow;
    border: 1px solid red;
}
#floating-element {
   float: left;
   width: 160px;
   height: 80px;
   background: lightgreen;
}

clear-example1.js


var floatValue1 = "left"; // FLOATING-LEMENT
var floatValue2 = "left"; // CURRENT-LEMENT
var clearValue2 = "none"; // CURRENT-LEMENT

function changeFloat1(event)  {
   floatValue1 = event.target.value;
   var myElement1 = document.getElementById("floating-element");
   myElement1.style.float = floatValue1;
   myElement1.innerHTML = "FLOATING-ELEMENT<br/>{float: "+ floatValue1+"}";
}
function changeFloat2(event)  {
   floatValue2 = event.target.value;
   var myElement2 = document.getElementById("current-element");
   myElement2.style.float = floatValue2;
   myElement2.innerHTML = "CURRENT-ELEMENT<br/>"
                         +"{float: "+ floatValue2+"}<br/>"
                         +"{clear: "+ clearValue2+"}";
}
function changeClear2(event)  {
   clearValue2 = event.target.value;
   var myElement2 = document.getElementById("current-element");
   myElement2.style.clear = clearValue2;
   myElement2.innerHTML = "CURRENT-ELEMENT<br/>"
                         +"{float: "+ floatValue2+"}<br/>"
                         +"{clear: "+ clearValue2+"}";
}

5- CSS Clear cho phần tử khối

CSS {clear: left | right} có thể áp dụng cho một phần tử khối (block element) – {display:block}, để ngăn chặn một phần tử nào đó nổi bên trái hoặc bên phải nó.

Chú ý: Trong code, phần tử khối áp dụng CSS {clear: left | right} phải được viết sau phần tử nổi (Floating element).


<floating-element>
<current-element>

Nếu phần tử hiện tại (#current-element) là phần tử khối. Dưới đây là các hình minh họa các tình huống có thể xẩy ra:


clear-example2.html


<!DOCTYPE html>
<html>
   <head>
      <title>CSS Clear</title>
      <meta charset="UTF-8"/>
      <link rel="stylesheet" href="clear-example2.css" />
      <script src="clear-example2.js"> </script>
   </head>
   <body>
       <h1>CSS Clear</h1>
       <div class="option">
         #floating-element <br/><br/>
         <input type="radio" name="f-radio" value="left" onclick="changeFloat1(event)" checked/> float:left <br/>
         <input type="radio" name="f-radio" value="right" onclick="changeFloat1(event)"/> float:right
       </div>
       <div class="option">
         #current-element <br/><br/>
         <input type="radio" name="c2-radio" value="none" onclick="changeClear2(event)" checked/> clear:none <br/>
         <input type="radio" name="c2-radio" value="left" onclick="changeClear2(event)"/> clear:left <br/>
         <input type="radio" name="c2-radio" value="right" onclick="changeClear2(event)"/> clear:right
       </div> 
       <hr/>
       <p style="color:blue;">
          CASE: #current-element is a Block Element.
       </p>
       <div class = "container">
            <div id = "floating-element">
              FLOATING-ELEMENT <br/>
              {float: left}
            </div>
            <div id = "current-element">
              CURRENT-ELEMENT
            </div>
       </div>
   </body>
</html>

clear-example2.css


.option {
  display: inline-block;
  width: 130px;
  margin-right: 5px;
  padding: 5px;
  border: 1px solid black;
}
.container {
  background-color: #eee;
  padding: 15px;
  height: 200px;
}
.container div {
   margin: 5px;
   padding:10px;
}
#current-element {
    height: 120px;
    margin: 10px;
    background: yellow;
    border: 1px solid red;
}
#floating-element {
   float: left;
   width: 160px;
   height: 80px;
   background: lightgreen;
}

clear-example2.js


var floatValue1 = "left"; // FLOATING-LEMENT
var clearValue2 = "none"; // CURRENT-LEMENT

function changeFloat1(event)  {
   floatValue1 = event.target.value;
   var myElement1 = document.getElementById("floating-element");
   myElement1.style.float = floatValue1;
   myElement1.innerHTML = "FLOATING-ELEMENT<br/>{float: "+ floatValue1+"}";
}
function changeClear2(event)  {
   clearValue2 = event.target.value;
   var myElement2 = document.getElementById("current-element");
   myElement2.style.clear = clearValue2;
   myElement2.innerHTML = "CURRENT-ELEMENT<br/>"
                         +"{clear: "+ clearValue2+"}";
}

Các phần tử nổi (floating element) đôi khi không tham gia vào việc làm tăng chiều cao cho phần tử cha, vì vậy bạn sẽ thấy một tình huống giống như hình minh họa dưới đây:

Thêm một phần tử khối với CSS {clear:both} như một phần tử con cuối cùng của phần tử cha sẽ giúp phần tử cha có chiều cao phù hợp, đủ để chứa hết tất cả các phần tử con.


<div class = "container">
    <div id = "floating-element1">
      ...
    </div>
    <div id = "floating-element2">
      ...
    </div>
    <div style="clear:both;"></div>
</div>

clear-example3.html


<!DOCTYPE html>
<html>
   <head>
      <title>CSS Clear</title>
      <meta charset="UTF-8"/>
      <link rel="stylesheet" href="clear-example3.css" />
      <script src="clear-example3.js"> </script>
   </head>
   <body>
       <h1>CSS Clear</h1>
       <div class="option">
         <p style="color:red">#current-element</p>
         <input type="radio" name="c2-radio" value="none" onclick="changeClear(event)" checked/> clear:none <br/>
         <input type="radio" name="c2-radio" value="left" onclick="changeClear(event)"/> clear:left <br/>
         <input type="radio" name="c2-radio" value="right" onclick="changeClear(event)"/> clear:right <br/>
         <input type="radio" name="c2-radio" value="both" onclick="changeClear(event)"/> clear:both
       </div>
       <hr/>
       <p style="color:red;">
          CASE: #current-element is a Block Element.
       </p>
       <div class = "container">
            <div id = "floating-element1">
              FLOATING 1 <br/>
              {float: right}
            </div>
            <div id = "floating-element2">
              FLOATING 2 <br/>
              {float: left}
            </div>
            <div id= "current-element">
            </div>
       </div>
   </body>
</html>

clear-example3.css


.option {
  display: inline-block;
  margin-right: 5px;
  padding: 5px;
  border: 1px solid black;
}
.container {
  background-color: #eee;
  padding: 5px;
  border: 1px solid blue;
}
#floating-element1 {
   float: right;
   width: 100px;
   height: 40px;
   background: lightblue;
}
#floating-element2 {
   float: left;
   width: 120px;
   height: 80px;
   background: lightgreen;
} 
#current-element {
   border: 1px solid red;
}

clear-example3.js


// Change CSS Clear for #current-element.
function changeClear(event)  {
   var clearValue = event.target.value;
   var myElement = document.getElementById("current-element");
   myElement.style.clear = clearValue;
}

Chú ý: CSS {clear: left | right} sẽ không hoạt động nếu bạn áp dụng nó cho một phần tử nội tuyến (inline) hoặc nội tuyến khối (inline-block)

Ví dụ, CSS clear không làm việc khi bạn áp dụng nó cho phần tử nội tuyến (Inline element):

clear-not-work-example1.html


<!DOCTYPE html>
<html>
   <head>
      <title>CSS Clear</title>
      <meta charset="UTF-8"/>
      <link rel="stylesheet" href="clear-not-work-example1.css" />
   </head>
   <body>
       <h3>CSS Clear does not work with Inline and Inline-block elements</h3> 
       <div class = "container">
            <div id = "floating-element">
              FLOATING <br/>
              {float: left}
            </div>
            <div id = "current-element">
              (Inline Element) - {clear: left} -
              Apollo 11 was the spaceflight that landed the first humans,
              Americans Neil Armstrong and Buzz Aldrin,
              on the Moon on July 20, 1969, at 20:18 UTC.
              Armstrong became the first to step onto the lunar
              surface 6 hours later on July 21 at 02:56 UTC.

              Armstrong spent about three and a half two
              and a half hours outside the spacecraft,
              Aldrin slightly less; and together they
              collected 47.5 pounds (21.5 kg) of lunar material
              for return to Earth. A third member of the mission,...
            </div>
       </div>
   </body>
</html>

clear-not-work-example1.css


.container {
  background-color: #eee;
  padding: 15px;
  height: 200px;
}
#floating-element {
   float: left;
   width: 150px;
   height: 80px;
   background: lightgreen;
   padding:5px;
   margin: 5px;
}
#current-element {
   border: 1px solid lightblue;
   padding: 5px;
   display: inline;
   clear: left; /** Not work with Inline, Inline-Block Element */
}

Ví dụ, CSS clear không làm việc khi bạn áp dụng nó cho phần tử nội tuyến khối (Inline-block element):

clear-not-work-example2.html


<!DOCTYPE html>
<html>
   <head>
      <title>CSS Clear</title>
      <meta charset="UTF-8"/>
      <link rel="stylesheet" href="clear-not-work-example2.css" />
   </head>
   <body>
       <h3>CSS Clear does not work with Inline and Inline-block elements</h3> 
       <div class = "container">
            <div id = "floating-element">
              FLOATING <br/>
              {float: left}
            </div>
            <div id = "current-element">
              (Inline-Block Element)  - {clear: left} -
              Apollo 11 was the spaceflight that landed the first humans,
              Americans Neil Armstrong and Buzz Aldrin,
              on the Moon on July 20, 1969, at 20:18 UTC.
              Armstrong became the first to step onto the lunar
              surface 6 hours later on July 21 at 02:56 UTC.
            </div>
       </div>
   </body>
</html>

clear-not-work-example2.css


.container {
  background-color: #eee;
  padding: 15px;
  height: 200px;
}
#floating-element {
   float: left;
   width: 140px;
   height: 80px;
   background: lightgreen;
   padding:5px;
   margin: 5px;
}
#current-element {
   border: 1px solid lightblue;
   padding: 5px;
   width: 200px;
   display: inline-block;
   clear: left; /** Not work with Inline, Inline-Block Element */
}