Flexbox——Flex容器



要在應用程式中使用Flexbox,你需要使用display屬性建立/定義一個flex容器。

用法——

display: flex | inline-flex

此屬性接受兩個值

  • flex——生成塊級flex容器。

  • inline-flex——生成內聯flex容納框。

現在,我們將使用一些例子,看看如何使用display屬性。

Flex

將此值傳遞給display屬性後,一個塊級flex容器將被建立。它佔據父容器(瀏覽器)的全部寬度。

下列示例演示瞭如何建立一個塊級flex容器。在此,我們建立了六個不同顏色的盒子,並使用flex容器容納它們。

<!doctype html>
<html lang = "en">
   <style>
      .box1{background:green;}
      .box2{background:blue;}
      .box3{background:red;}
      .box4{background:magenta;}
      .box5{background:yellow;}
      .box6{background:pink;}
      
      .container{
         display:flex;
      }
      .box{
         font-size:35px;
         padding:15px;
      }
   </style>
   
   <body>
      <div class = "container">
         <div class = "box box1">One</div>
         <div class = "box box2">two</div>
         <div class = "box box3">three</div>
         <div class = "box box4">four</div>
         <div class = "box box5">five</div>
         <div class = "box box6">six</div>
      </div>
   </body>
</html>

它將產生以下結果——

由於我們向display屬性給出了flex值,容器使用容器(瀏覽器)的寬度。

可以透過如下所示向容器新增邊框,觀察到這一點。

.container {
   display:inline-flex;
   border:3px solid black;
}

它將產生以下結果——

內聯flex

將此值傳遞給display屬性後,一個內聯flex容器將被建立。它只佔用內容所需的空間。

下列示例演示瞭如何建立一個內聯flex容器。在此,我們建立了六個不同顏色的盒子,並使用flex容器容納它們。

<!doctype html>
<html lang = "en">
   <style>
      .box1{background:green;}
      .box2{background:blue;}
      .box3{background:red;}
      .box4{background:magenta;}
      .box5{background:yellow;}
      .box6{background:pink;}
      
      .container{
         display:inline-flex;
         border:3px solid black;
      }
      .box{
         font-size:35px;
         padding:15px;
      }
   </style>
   
   <body>
      <div class = "container">
         <div class = "box box1">One</div>
         <div class = "box box2">two</div>
         <div class = "box box3">three</div>
         <div class = "box box4">four</div>
         <div class = "box box5">five</div>
         <div class = "box box6">six</div>
      </div>
   </body>
</html>

它將產生以下結果——

由於我們使用內聯flex容器,它只佔據包裝其元素所需的空間。

廣告
© . All rights reserved.