Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Apline Tailwind Dropdown
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<link rel="stylesheet" href="./build.css" />
<script src="https://cdn.jsdelivr.net/gh/alpinejs/alpine@v2.x.x/dist/alpine.min.js" defer></script>
</head>
<body class="p-12 m-12">
<div x-data="dropdown()">
<button class="dropdown-trigger" id="open-color-menu" x-spread="trigger">
Open Dropdown
</button>
<div class="dropdown-list" id="color-menu" x-spread="dropdown" x-cloak>
<a href="#" class="dropdown-item">Red</a>
<a href="#" class="dropdown-item">Blue</a>
<a href="#" class="dropdown-item">Green</a>
</div>
</div>
<script>
window.dropdown = function () {
return {
open: false,
trigger: {
["@keydown.escape"]() {
this.open = false;
},
["@click"]() {
this.open = true;
},
},
dropdown: {
["@keydown.escape"]() {
this.open = false;
},
["x-show.transition"]() {
return this.open;
},
["@click.away"]() {
this.open = false;
},
},
};
};
</script>
</body>
</html>
@tailwind base;
@tailwind components;
[x-cloak] {
@apply hidden;
}
.dropdown-trigger {
@apply inline-block py-2 px-4 rounded-md bg-purple-700 text-white;
}
.dropdown-list {
@apply absolute z-10 shadow-md w-56 flex flex-col border border-solid border-gray-200 bg-white p-2 rounded;
}
.dropdown-item {
@apply relative flex px-2 py-1 items-center text-gray-800;
}
@tailwind utilities;
{
"name": "alpine-tailwind-dropdown",
"scripts": {
"start": "postcss ./main.css -o ./build.css --watch --verbose --no-map --use tailwindcss",
},
"dependencies": {
"postcss-cli": "^7.1.1",
"tailwindcss": "^1.6.2"
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment