點燈坊

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

Using translate to Move Element

Sam Xiao's Avatar 2022-01-08

Not only use x-show to hide the element, but we can also use -translate-x-full or -translate-y-full to hide the element.

Version

Alpine 3.7
TailwindCSS 3.0

translate-x-4

translate000

TailwindCSS is horizontally shifted.

<!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="translate-x-4">TailwindCSS</div>
</body>
</html>
  • translate-x-4 : move the element to the horizontal direction

translate-x-1/2

translate001

TailwindCSS is horizontally shifted by the half of parent width.

<!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="translate-x-1/2">TailwindCSS</div>
</body>
</html>
  • translate-x-1/2 : move the element by the half of parent width

-translate-x-full

translate002

TailwindCSS is gone.

<!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="translate-x-full">TailwindCSS</div>
</body>
</html>
  • translate-x-full : move the element outside of the current page

transition

translate003

Instead of using x-show, using translate-x-full to toggle the element.

<!doctype html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://unpkg.com/alpinejs" defer></script>
  <script src="https://cdn.tailwindcss.com"></script>
  <title>TailwindCSS</title>
</head>
<body x-data="{ isShow: true }">
  <button class="text-gray-800 bg-gray-200 rounded-lg px-3 py-1" @click="isShow = !isShow">Toggle</button>
  <div class="transition duration-500" :class="isShow || '-translate-x-full'">TailwindCSS</div>
</body>
</html>

Line 10

<body x-data="{ isShow: true }">
  • isShow : control showing the element or not

Line 11

<button class="text-gray-800 bg-gray-200 rounded-lg px-3 py-1" @click="isShow = !isShow">Toggle</button>

<button> to toggle isShow state.

Line 12

<div class="transition duration-500" :class="isShow || '-translate-x-full'">TailwindCSS</div>
  • -transition-x-full : if isShow is false, move the element outside of the current page
  • transition duration-500 : use CSS transition to slow down the toggling effect

Conclusion

  • We can use -translate-x-full or -translate-y-full to hide the element

Reference

TailwindCSS, translate