Show dev: Я создал коллекцию компонентов popover с помощью Tailwind CSS

Здравствуйте, разработчики 👋

Я и мои друзья создали коллекцию компонентов popover, используя классы фреймворка Tailwind CSS и JavaScript интеграцию с библиотекой компонентов Flowbite.

Popover — это всплывающее окно, которое появляется при наведении или нажатии на элемент триггера, где вы можете показать дополнительную информацию, например, абзац, информацию о профиле пользователя и многое другое.

Вот предварительный просмотр одного из компонентов popover:

В этой статье я покажу вам коллекцию примеров popover и то, как вы можете начать использовать их в своих проектах.

Начало работы

Прежде всего, вам необходимо убедиться, что в вашем проекте установлены Tailwind CSS и Flowbite.

Установите Tailwind CSS

Для установки Tailwind CSS вы можете воспользоваться руководством по быстрому запуску или выполнить следующие шаги:

Установите tailwindcss через NPM:

npm install -D tailwindcss
npx tailwindcss init
Войдите в полноэкранный режим Выйти из полноэкранного режима

Настройте пути к шаблонам в файле tailwind.config.js:

/** @type {import('tailwindcss').Config} */ 
module.exports = {
  content: ["./src/**/*.{html,js}"],
  theme: {
    extend: {},
  },
  plugins: [],
}
Войти в полноэкранный режим Выйти из полноэкранного режима

Создайте новый файл src/input.css и добавьте следующее содержимое:

@tailwind base;
@tailwind components;
@tailwind utilities;
Вход в полноэкранный режим Выйти из полноэкранного режима

Скомпилируйте и проследите за изменениями в CSS:

npx tailwindcss -i ./src/input.css -o ./dist/output.css --watch
Войти в полноэкранный режим Выйти из полноэкранного режима

Отлично! Теперь, когда у вас установлен Tailwind CSS, мы можем приступить к установке Flowbite.

Установите Flowbite

Установите Flowbite в качестве зависимости с помощью NPM, выполнив следующую команду:

npm i flowbite
Войти в полноэкранный режим Выйти из полноэкранного режима

Требуйте Flowbite как плагин в файле tailwind.config.js:

module.exports = {

    plugins: [
        require('flowbite/plugin')
    ]

}
Войти в полноэкранный режим Выйти из полноэкранного режима

Включите основной файл JavaScript для работы интерактивных элементов:

<script src="../path/to/flowbite/dist/flowbite.js"></script>
Войти в полноэкранный режим Выход из полноэкранного режима

Дополнительно к собственным данным content необходимо добавить flowbite для применения классов из интерактивных элементов в файле tailwind.config.js:

module.exports = {

    content: [
        "./node_modules/flowbite/**/*.js"
    ]

}
Вход в полноэкранный режим Выход из полноэкранного режима

Если вы используете Webpack или другие бандлеры, вы также можете импортировать его следующим образом:

import 'flowbite';
Войти в полноэкранный режим Выйти из полноэкранного режима

Включение через CDN

Самый быстрый способ начать работу с FlowBite — просто включить CSS и JavaScript в ваш проект через CDN.

Потребуйте следующую минифицированную таблицу стилей внутри тега head:

<link rel="stylesheet" href="https://unpkg.com/flowbite@{{< current_version >}}/dist/flowbite.min.css" />
Вход в полноэкранный режим Выход из полноэкранного режима

И включите следующий файл JavaScript до конца элемента body:

<script src="https://unpkg.com/flowbite@{{< current_version >}}/dist/flowbite.js"></script>
Войти в полноэкранный режим Выйти из полноэкранного режима

Потрясающе! Теперь, когда в вашем проекте установлены Tailwind CSS и Flowbite, вы можете сразу же использовать коллекцию компонентов Popover.

Tailwind CSS Popover

Инициализируйте новый popover, добавив атрибут данных data-popover-target="{elementId}" к триггерному элементу, где elementId — это id компонента popover.

Исходный код:

<button data-popover-target="popover-default" type="button" class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800">Default popover</button>
<div id="popover-default" role="tooltip" class="inline-block absolute invisible z-10 w-64 text-sm font-light text-gray-500 bg-white rounded-lg border border-gray-200 shadow-sm opacity-0 transition-opacity duration-300 dark:text-gray-400 dark:border-gray-600 dark:bg-gray-800">
    <div class="py-2 px-3 bg-gray-100 rounded-t-lg border-b border-gray-200 dark:border-gray-600 dark:bg-gray-700">
        <h3 class="font-semibold text-gray-900 dark:text-white">Popover title</h3>
    </div>
    <div class="py-2 px-3">
        <p>And here's some amazing content. It's very engaging. Right?</p>
    </div>
    <div data-popper-arrow></div>
</div>
Вход в полноэкранный режим Выход из полноэкранного режима

Вот еще один пример, где вместо описания можно использовать информацию о профиле пользователя:

Исходный код:

<button data-popover-target="popover-user-profile" type="button" class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800">User profile</button>
<div id="popover-user-profile" role="tooltip" class="inline-block absolute invisible z-10 w-64 text-sm font-light text-gray-500 bg-white rounded-lg border border-gray-200 shadow-sm opacity-0 transition-opacity duration-300 dark:text-gray-400 dark:bg-gray-800 dark:border-gray-600">
    <div class="p-3">
        <div class="flex justify-between items-center mb-2">
            <a href="#">
                <img class="w-10 h-10 rounded-full" src="/docs/images/people/profile-picture-1.jpg" alt="Jese Leos">
            </a>
            <div>
                <button type="button" class="text-white bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:ring-blue-300 font-medium rounded-lg text-xs px-3 py-1.5 dark:bg-blue-600 dark:hover:bg-blue-700 focus:outline-none dark:focus:ring-blue-800">Follow</button>
            </div>
        </div>
        <p class="text-base font-semibold leading-none text-gray-900 dark:text-white">
            <a href="#">Jese Leos</a>
        </p>
        <p class="mb-3 text-sm font-normal">
            <a href="#" class="hover:underline">@jeseleos</a>
        </p>
        <p class="mb-4 text-sm font-light">Open-source contributor. Building <a href="#" class="text-blue-600 dark:text-blue-500 hover:underline">flowbite.com</a>.</p>
        <ul class="flex text-sm font-light">
            <li class="mr-2">
                <a href="#" class="hover:underline">
                    <span class="font-semibold text-gray-900 dark:text-white">799</span>
                    <spa>Following</span>
                </a>
            </li>
            <li>
                <a href="#" class="hover:underline">
                    <span class="font-semibold text-gray-900 dark:text-white">3,758</span>
                    <span>Followers</span>
                </a>
            </li>
        </ul>
    </div>
    <div data-popper-arrow></div>
</div>
Войти в полноэкранный режим Выход из полноэкранного режима

Вот пример, где вы можете показать описание и изображение, аналогично всплывающим окнам Википедии:

Исходный код:

<p class="font-light text-gray-500 dark:text-gray-400">Due to its central geographic location in Southern Europe, <a href="#" class="text-blue-600 underline dark:text-blue-500 hover:no-underline" data-popover-target="popover-image">Italy</a> has historically been home to myriad peoples and cultures. In addition to the various ancient peoples dispersed throughout what is now modern-day Italy, the most predominant being the Indo-European Italic peoples who gave the peninsula its name, beginning from the classical era, Phoenicians and Carthaginians founded colonies mostly in insular Italy</p>
<div id="popover-image" role="tooltip" class="inline-block absolute invisible z-10 w-96 text-sm font-light text-gray-500 bg-white rounded-lg border border-gray-200 shadow-sm opacity-0 transition-opacity duration-300 dark:text-gray-400 dark:bg-gray-800 dark:border-gray-600">
    <div class="grid grid-cols-5">
        <div class="col-span-3 p-3">
            <div class="space-y-2">
                <h3 class="font-semibold text-gray-900 dark:text-white">About Italy</h3>
                <p>Italy is located in the middle of the Mediterranean Sea, in Southern Europe it is also considered part of Western Europe. A unitary parliamentary republic with Rome as its capital and largest city.</p>
                <a href="#" class="flex items-center font-medium text-blue-600 dark:text-blue-500 dark:hover:text-blue-600 hover:text-blue-700">Read more <svg class="ml-1 w-4 h-4" aria-hidden="true" fill="currentColor" viewBox="0 0 20 20" xmlns="http://www.w3.org/2000/svg"><path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd"></path></svg></a>
            </div>
        </div>
        <img src="/docs/images/popovers/italy.png" class="col-span-2 h-full" alt="Italy map" />
    </div>
    <div data-popper-arrow></div>
</div>
Войти в полноэкранный режим Выйти из полноэкранного режима

Размещение

Вы также можете задать положение компонента popover относительно элемента триггера, используя атрибут данных data-popover-placement="{top|right|bottom "left}" и его значения.

Исходный код:


<button data-popover-target="popover-top" data-popover-placement="top" type="button" class="text-white mb-3 bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800">Top popover</button>
<div id="popover-top" role="tooltip" class="inline-block absolute invisible z-10 w-64 text-sm font-light text-gray-500 bg-white rounded-lg border border-gray-200 shadow-sm opacity-0 transition-opacity duration-300 dark:text-gray-400 dark:border-gray-600 dark:bg-gray-800" data-popper-reference-hidden="" data-popper-escaped="" data-popper-placement="top" style="position: absolute; inset: auto auto 0px 0px; margin: 0px; transform: translate3d(59.5px, 106px, 0px);">
    <div class="py-2 px-3 bg-gray-100 rounded-t-lg border-b border-gray-200 dark:border-gray-600 dark:bg-gray-700">
        <h3 class="font-semibold text-gray-900 dark:text-white">Popover top</h3>
    </div>
    <div class="py-2 px-3">
        <p>And here's some amazing content. It's very engaging. Right?</p>
    </div>
    <div data-popper-arrow="" style="position: absolute; left: 0px; transform: translate3d(123px, 0px, 0px);"></div>
</div>
<button data-popover-target="popover-right" data-popover-placement="right" type="button" class="text-white mb-3 bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800">Right popover</button>
<div id="popover-right" role="tooltip" class="inline-block absolute invisible z-10 w-64 text-sm font-light text-gray-500 bg-white rounded-lg border border-gray-200 shadow-sm opacity-0 transition-opacity duration-300 dark:text-gray-400 dark:border-gray-600 dark:bg-gray-800" data-popper-reference-hidden="" data-popper-escaped="" data-popper-placement="right" style="position: absolute; inset: 0px auto auto 0px; margin: 0px; transform: translate3d(409.5px, 29px, 0px);">
    <div class="py-2 px-3 bg-gray-100 rounded-t-lg border-b border-gray-200 dark:border-gray-600 dark:bg-gray-700">
        <h3 class="font-semibold text-gray-900 dark:text-white">Popover right</h3>
    </div>
    <div class="py-2 px-3">
        <p>And here's some amazing content. It's very engaging. Right?</p>
    </div>
    <div data-popper-arrow="" style="position: absolute; top: 0px; transform: translate3d(0px, 85px, 0px);"></div>
</div>
<button data-popover-target="popover-bottom" data-popover-placement="bottom" type="button" class="text-white mb-3 bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800">Bottom popover</button>
<div id="popover-bottom" role="tooltip" class="inline-block absolute invisible z-10 w-64 text-sm font-light text-gray-500 bg-white rounded-lg border border-gray-200 shadow-sm opacity-0 transition-opacity duration-300 dark:text-gray-400 dark:border-gray-600 dark:bg-gray-800" data-popper-reference-hidden="" data-popper-escaped="" data-popper-placement="top" style="position: absolute; inset: auto auto 0px 0px; margin: 0px; transform: translate3d(361px, 106px, 0px);">
    <div class="py-2 px-3 bg-gray-100 rounded-t-lg border-b border-gray-200 dark:border-gray-600 dark:bg-gray-700">
        <h3 class="font-semibold text-gray-900 dark:text-white">Popover bottom</h3>
    </div>
    <div class="py-2 px-3">
        <p>And here's some amazing content. It's very engaging. Right?</p>
    </div>
    <div data-popper-arrow="" style="position: absolute; left: 0px; transform: translate3d(123px, 0px, 0px);"></div>
</div>
<button data-popover-target="popover-left" data-popover-placement="left" type="button" class="text-white mb-3 bg-blue-700 hover:bg-blue-800 focus:ring-4 focus:outline-none focus:ring-blue-300 font-medium rounded-lg text-sm px-5 py-2.5 text-center dark:bg-blue-600 dark:hover:bg-blue-700 dark:focus:ring-blue-800">Left popover</button>
<div id="popover-left" role="tooltip" class="inline-block absolute invisible z-10 w-64 text-sm font-light text-gray-500 bg-white rounded-lg border border-gray-200 shadow-sm opacity-0 transition-opacity duration-300 dark:text-gray-400 dark:border-gray-600 dark:bg-gray-800" data-popper-reference-hidden="" data-popper-escaped="" data-popper-placement="left" style="position: absolute; inset: 0px 0px auto auto; margin: 0px; transform: translate3d(-261px, 29px, 0px);">
    <div class="py-2 px-3 bg-gray-100 rounded-t-lg border-b border-gray-200 dark:border-gray-600 dark:bg-gray-700">
        <h3 class="font-semibold text-gray-900 dark:text-white">Popover left</h3>
    </div>
    <div class="py-2 px-3">
        <p>And here's some amazing content. It's very engaging. Right?</p>
    </div>
    <div data-popper-arrow="" style="position: absolute; top: 0px; transform: translate3d(0px, 85px, 0px);"></div>
</div>
Вход в полноэкранный режим Выход из полноэкранного режима

Заключение

Вы можете ознакомиться со всей документацией и примерами компонента Tailwind CSS Popover Component в самой библиотеке Flowbite.

Кредиты:

  • Tailwind CSS
  • Flowbite

Оцените статью
devanswers.ru
Добавить комментарий