點燈坊

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

Making inline-block Horizontal Center

Sam Xiao's Avatar 2022-01-19

Since inline-block makes the width of the element shrink to fit the content, we can’t use inline-block mx-auto to make the element horizontal center.

Version

TailwindCSS 3.0

text-center

center000

TailwindCSS in inline-block, which is horizontal center.

<!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="text-center">
    <div class="inline-block">TailwindCSS</div>
  </div>
</body>
</html>

Line 10

<div class="text-center">
  <div class="inline-block">TailwindCSS</div>
</div>
  • inline-block : make the element display: inline-block
  • text-center : inline-block makes the element shrink to fit the content. So we can use text-center to make this child element horizontal center

flex

center000

We can also use flex justify-center to make an inline-block horizontal center.

<!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 justify-center">
    <div class="inline-block">TailwindCSS</div>
  </div>
</body>
</html>

Line 10

<div class="flex justify-center">
  <div class="inline-block">TailwindCSS</div>
</div>
  • flex : make parent element as Flex Container and child element as Flex Item
  • justify-center : all Flex Items are placed at the center with no spaces
  • inline-block : make the element display: inline-block

Conclusion

  • Although inline-block has some features of block, we can’t use inline-block mx-auto to make the element horizontal center