Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> CSS

Các loại Box được tạo ra trong CSS

Mỗi phần tử trong cây tài liệu (document tree) sau khi được xử lý theo mô hình định dạng trực quan (visual formatting model) sẽ tạo ra một hoặc nhiều hộp (boxes). Mỗi hộp được tạo ra có các thuộc tính CSS nhất định liên kết với nó và được hiển thị tương ứng trong HTML.

Các loại box được tạo ra trong CSS bao gồm:

  • Block-level Elements và Block Boxes
    • Anonymous block boxes
  • Inline-level Elements và Inline Boxes
    • Anonymous inline boxes

Ví dụ 1: Block-level Elements và Block Boxes

<!DOCTYPE html>
<html>
<head>
<title>CSS Block-level Elements and Block Boxes</title>
<style>
  form { width: 70%; margin: 0 auto; text-align: center; }
  * { padding: 2px; box-sizing: border-box; }
  input[type="button"] { border-radius: 10px; }
  .child { height: 40px; width: 100%; color: white; border: 4px solid black; }
  .child:nth-of-type(1) { background-color: #FF8A00; }
  .child:nth-of-type(2) { background-color: #F44336; }
  .child:nth-of-type(3) { background-color: #C303C3; }
  .child:nth-of-type(4) { background-color: #4CAF50; }
  .child:nth-of-type(5) { background-color: #03A9F4; }
  .child:nth-of-type(6) { background-color: #FEDC11; }
</style>
</head>
<body>
  <form>
    <fieldset>
      <legend>CSS Block-level Elements and Block Boxes</legend>
      <div id="container">
        Color Orange <div class="child"></div>
        Color Red <div class="child"></div>
        Color Violet <div class="child"></div>
      </div><br>
    </fieldset>
  </form>
</body>
</html>

Kết quả

Các loại Box được tạo ra trong CSS

Ví dụ 2: Inline-level Elements và Inline Boxes

<!DOCTYPE html>
<html>
<head>
<title>CSS Inline-level Elements and Inline Boxes</title>
<style>
  form { width: 70%; margin: 0 auto; text-align: center; }
  * { padding: 2px; }
  input[type="button"] { border-radius: 10px; }
  .child { color: white; border: 4px solid black; }
  .child:nth-of-type(1) { background-color: #FF8A00; }
  .child:nth-of-type(2) { background-color: #F44336; }
  .child:nth-of-type(3) { background-color: #C303C3; }
  .child:nth-of-type(4) { background-color: #4CAF50; }
  .child:nth-of-type(5) { background-color: #03A9F4; }
  .child:nth-of-type(6) { background-color: #FEDC11; }
</style>
</head>
<body>
  <form>
    <fieldset>
      <legend>CSS Inline-level Elements and Inline Boxes</legend>
      <div>
        <span class="child">Orange</span> Color
        <span class="child">Red</span> Color
        <span class="child">Violet</span> Color
      </div><br>
    </fieldset>
  </form>
</body>
</html>

Kết quả

Các loại Box được tạo ra trong CSS

Phân biệt:

Đặc điểmBlock BoxInline Box
Ngắt dòngCó (trước và sau)Không
Chiều rộngToàn bộ containerChỉ vừa nội dung
Width/HeightCó tác dụngKhông tác dụng
Ví dụdiv, p, h1-h6span, strong, em, a