CSS 中的內聯級元素和內聯框


內聯級元素的 CSS display 屬性設定為“inline”、“inline-table”或“inline-block”,這些元素不會在其上下強制換行。每個內聯級元素都會生成內聯級框,它是定位方案的一部分,並且包含子框。

內聯框是其內容遵循內聯格式化上下文的框。內聯框被分成多個內聯框,而那些從未被分割的內聯框稱為原子內聯級框。

匿名內聯框是開發人員無法控制的那些框。如果一個塊級框包含一些純文字和其他內聯級框,則內聯級框周圍的純文字遵循內聯格式化上下文,幷包含在匿名內聯框中。

內聯級與塊級

內聯級元素不會在其上下強制換行,並且僅佔用內容所需的寬度。例如 - 跨度(<span>)、強元素(<strong>)

塊級元素在其上下強制換行,並佔用可用寬度,即使其內容不需要也一樣。例如:分割槽(<div>)、標題(<h1> 到 <h6>)等。

讓我們來看一個內聯級框生成的示例 -

示例

在這個示例中,我們將圍繞內聯級元素 <em> 進行操作 -

<!DOCTYPE html>
<html>
<head>
   <title>em element</title>
   <style>
      form {
         width:70%;
         margin: 0 auto;
         text-align: center;
      }
      * {
         padding: 2px;
         margin:5px;
      }
      input[type="button"] {
         border-radius: 10px;
      }
      em{
         background-color: #FF8A00;
      }
   </style>
</head>
<body>
   <form>
      <fieldset>
         <legend>em-element</legend>
         <label for="textSelect">Formatter: </label>
         <input id="textSelect" type="text" placeholder="John Doe">
         <input type="button" onclick="convertItalic()" value="Check">
         <div id="divDisplay"></div>
      </fieldset>
   </form>
   <script>
      var divDisplay = document.getElementById("divDisplay");
      var textSelect = document.getElementById("textSelect");
      function convertItalic() {
         for(i=0; i<2; i++){
            var italicObject = document.createElement("EM");
            var italicText = document.createTextNode(textSelect.value);
            italicObject.appendChild(italicText);
            divDisplay.appendChild(italicObject);
         }
      }
   </script>
</body>
</html>

示例

在這個示例中,我們將圍繞內聯級元素 <span> 進行操作 -

<!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;
      }
   </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>

更新於: 2023-12-21

356 次瀏覽

開啟你的 職業生涯

透過完成課程獲得認證

開始學習
廣告

© . All rights reserved.