點燈坊

失くすものさえない今が強くなるチャンスよ

Flexbox Overview

Sam Xiao's Avatar 2022-01-21

Flexbox is a new layout for CSS 3. We can use a simple way for layout instead of inline-block or float.

Version

TailwindCSS 3.0

Block

flex000

The width of every <div> is w-4/12, but it can’t display in one line.

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdn.tailwindcss.com"></script>
  <title>TailwindCSS</title>
</head>
<body>
  <div>
    <div class="w-4/12">1</div>
    <div class="w-4/12">2</div>
    <div class="w-4/12">3</div>
  </div>
</body>
</html>

Line 11

<div>
  <div class="w-4/12">1</div>
  <div class="w-4/12">2</div>
  <div class="w-4/12">3</div>
</div>

We can’t specify the width of to block element. Every block element occupies one line.

Horizontal Layout

flex001

3 <div>s are displayed in one line.

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdn.tailwindcss.com"></script>
  <title>TailwindCSS</title>
</head>
<body>
  <div class="flex">
    <div class="w-4/12">1</div>
    <div class="w-4/12">2</div>
    <div class="w-4/12">3</div>
  </div>
</body>
</html>

Line 10

<div class="flex">
  <div class="w-4/12">1</div>
  <div class="w-4/12">2</div>
  <div class="w-4/12">3</div>
</div>
  • flex : make parent element as Flex box and child element as Flex Item
  • We can specify the width to Flex Item
  • If the Flex Item without any width specified, the width is shrunk to fit the content width

flex makes the <div> displayed horizontally

Auto Shrink

flex002

Although we add margin to every Flex Item, it remains in one line.

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdn.tailwindcss.com"></script>
  <title>TailwindCSS</title>
</head>
<body>
  <div class="flex">
    <div class="w-4/12 m-2">1</div>
    <div class="w-4/12 m-2">2</div>
    <div class="w-4/12 m-2">3</div>
  </div>
</body>
</html>

Line 10

<div class="flex">
  <div class="w-4/12 m-2">1</div>
  <div class="w-4/12 m-2">2</div>
  <div class="w-4/12 m-2">3</div>
</div>

flex : shrink every Flex Items to fit Flex box.

Conclusion

  • Horizontal layout and auto shrink are the two major features of Flexbox