파란하늘의 지식창고
article thumbnail
반응형

이전에 Spring Boot 기반의 프로젝트에서 Thymeleaf와 함께 Tailwind CSS를 사용하는 방법에 대해 소개하였었다.

2023.11.16 - [Study/Java] - Spring Boot + Thymeleaf + Tailwind CSS 사용해보기

DaisyUI 소개

Tailwind CSS가 bootstrap보다 자유도가 높은 대신 많은 설정이 필요하기 때문에 이를 보완하기 위해 Daisy UI를 사용하였다.

DaisyUI는 Tailwind CSS기반에서 Bootstrap의 component 단위(Button, Form, Menu 같은...)의 CSS를 제공해 준다.

따라서 Component 단위로는 Tailwind CSS를 사용하면서 그 외의 CSS 설정은 Tailwind CSS를 같이 사용하여 코드의 중복을 줄일 수 있다.

이런 식으로 Component 단위의 Tailwind CSS 사용을 제공하는 framework는 DaisyUI 외에도 다양하게 많이 있다.
(정말 많이 있다...)

다만 유료이거나 혹은 React나 Vue, Svelte 등 FE Framework을 사용하는 경우 관련 Component를 제공하는 형태가 대다수여서 Tailwind CSS를 사용하면서 오픈소스이면서 Component 단위로 css 선언을 제공하는(prebuild 한) 라이브러리는 거의 없었다.
(DaisyUI 말고는 Kutty, Xtend UI 정도만 이런 형태로 사용이 가능했던 거 같다. 일일이 설치해 보고 사용해보지 않아서 정확하지 않음)

 

비슷한 질문이 reddit에 2년 전에 올라왔었는데 사람들이 찾아서 알려준 라이브러리들이 대부분 마이너하고 유지보수가 되지 않는 듯했다.
https://www.reddit.com/r/tailwindcss/comments/v8gsyv/any_more_prebuilt_component_libraries_like_daisyui/

DaisyUI Theme 사용

DaisyUI의 설치 방법을 소개하려던 것은 아니기 때문에 해당 내용은 생략한다.
관련 내용은 사이트 공식 문서를 참조하면 된다.
https://daisyui.com/docs/install/

 

Bootstrap처럼 componet 단위 CSS를 제공하면 얻게 되는 장점 중 하나가 theme를 사용할 수 있다는 점이다.

 

theme는 사전 정의한 component 단위 css에서 사용할 preset을 제공하여 사용자가 원하는 스타일의 UI를 사용할 수 있게 해 준다.
https://daisyui.com/docs/themes/

해당 페이지의 우상단의 theme를 선택하면 직관적으로 어떤 것인지 알 수 있다.

 

DaisyUI는 기본적으로 사용할 수 있도록 theme를 몇 가지 제공해주고 있다.
https://github.com/saadeghi/daisyui/blob/master/src/theming/themes.js

또한 사용자가 직접 원하는 custom theme를 정의하고 추가하여 사용할 수도 있다.

 

사용하려는 theme를 tailwind.config.js에 다음과 같이 추가하고 (아래는 Daisy UI가 제공하는 전체 theme 목록이다.)

/** @type {import('tailwindcss').Config} */
module.exports = {
    // ...
    daisyui: {
        themes: [
            "light",
            "dark",
            "cupcake",
            "bumblebee",
            "emerald",
            "corporate",
            "synthwave",
            "retro",
            "cyberpunk",
            "valentine",
            "halloween",
            "garden",
            "forest",
            "aqua",
            "lofi",
            "pastel",
            "fantasy",
            "wireframe",
            "black",
            "luxury",
            "dracula",
            "cmyk",
            "autumn",
            "business",
            "acid",
            "lemonade",
            "night",
            "coffee",
            "winter",
            "dim",
            "nord",
            "sunset",            
        ]
    },
}

이 중 사용하려는 Theme를 html에 다음과 같이 정의하기만 하면 된다.

<html data-theme="cupcake"></html>

Theme Change 사용하기

data-theme attribute의 값을 브라우저에서 개발자 모드에서 바꿔보면 변경된 theme가 적용되는 것을 확인할 수 있다.

 

여러 theme 중 원하는 theme를 사용자가 선택하여 변경할 수 있도록 하려면 theme change 라이브러리를 사용하면 data-theme 를 손쉽게 변경할 수 있다.
https://github.com/saadeghi/theme-change

 

html에 해당 js를 추가하고

<script src="https://unpkg.com/theme-change"></script>

theme change가 제공하는 data-choose-theme를 사용하여 select 메뉴를 다음과 같이 만들면 된다.

<select data-choose-theme>
  <option value="">Default</option>
  <option value="dark">Dark</option>
  <option value="light">Light</option>
  <option value="cupcake">Cupcake</option>
  <-- ... 이하 생략 -->
</select>

해당 메뉴를 select 하면 테마가 변경되고 변경된 theme가 브라우저의 localStorage에 저장되어 새로고침해도 계속 적용되는 것을 확인할 수 있다.

 

Spring기반에서 Thymeleaf를 사용한다면 다음과 같이 Java에서 theme 목록을 관리하여 select 메뉴에 내려줄 수 있다.

@UtilityClass
public class ThymeleafUtil {
    private static final String[] THEMES = new String[] {
            "light",
            "dark",
            "cupcake",
            "bumblebee",
            // 이하 생략
    };

    public static List<String> getThemeList() {
        return Arrays.asList(THEMES);
    }
}
<select class="select select-sm select-bordered" data-choose-theme>
    <option value="">Default</option>
    <option data-th-each="theme : ${thymeleafUtil.getThemeList()}" data-th-value="${theme}" data-th-text="${#strings.capitalize(theme)}"></option>
</select>

DaisyUI 홈페이지처럼 theme select 항목에 미리 보기 화면 표시하기

앞서 소개한 예에는 select로 theme 목록을 보여주고 그 중 선택을 하는 경우이다.


DaisyUI 홈페이지의 경우처럼 미리 볼 수 있는 화면을 보여주는 경우 다음과 같이 하면 된다.

앞서 Thymeleaf로 theme 목록을 내려주었는데 해당 목록을 그대로 사용한 경우이다.
(DaisyUI 홈페이지의 theme 선택 항목 코드를 살짝 수정하였다.)

<div title="Change Theme" class="dropdown dropdown-end">
    <div tabindex="0" class="btn btn-ghost h-14 rounded-none">
        <span>Theme</span>
        <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke-width="1.5" stroke="currentColor" class="w-3 h-3">
          <path stroke-linecap="round" stroke-linejoin="round" d="m19.5 8.25-7.5 7.5-7.5-7.5" />
        </svg>
    </div>
    <div tabindex="0" class="dropdown-content z-[1] bg-base-200 top-px h-[28.6rem] max-h-[calc(100vh-10rem)] w-56 overflow-y-auto mt-16">
        <div class="grid gap-3 p-3">
            <button
                class="text-start"
                data-th-each="theme : ${thymeleafUtil.getThemeList()}"
                data-th-data-set-theme="${theme}"
                data-act-class="[&_svg]:visible">
                <span data-th-data-theme="${theme}" class="rounded-btn block w-full font-sans">
                    <span class="grid">
                        <span class="flex gap-2 px-4 py-3">
                            <svg xmlns="http://www.w3.org/2000/svg" width="16" height="16" viewBox="0 0 24 24" fill="currentColor" class="invisible h-3 w-3 shrink-0">
                                <path d="M20.285 2l-11.285 11.567-5.286-5.011-3.714 3.716 9 8.728 15-15.285z"></path>
                            </svg>
                            <span class="flex-grow text-sm" data-th-text="${theme}"></span>
                            <span class="flex h-full gap-1">
                                <span class="bg-primary rounded-badge w-2"></span>
                                <span class="bg-secondary rounded-badge w-2"></span>
                                <span class="bg-accent rounded-badge w-2"></span>
                                <span class="bg-neutral rounded-badge w-2"></span>
                            </span>
                        </span>
                    </span>
                </span>
            </button>
        </div>
    </div>
</div>

Custom theme 사용하기

DaisyUI가 제공하는 Theme가 아닌 custom 한 theme의 사용하는 방법도 간단하다.

앞서 잠깐 언급하였던 DaisyUI가 제공하는 theme 설정을 참고하여 custom theme 설정을 만들어 tailwind.config.js 에 추가하면 된다.
https://github.com/saadeghi/daisyui/blob/master/src/theming/themes.js

 

대략 다음과 같이 추가한다.

/** @type {import('tailwindcss').Config} */
module.exports = {
    // ...
    daisyui: {
        themes: [
            "light",
            "dark",
            // ...
            {
                bluesky : {
                    "primary": "#ff00ff",
                    "secondary": "#ffffff",
                    "accent": "#ffffff",
                    "neutral": "#ffffff",
                    "base-100": "#ffffff",
                    "info": "#ffffff",
                    "success": "#00ffff",
                    "warning": "#ffffff",
                    "error": "#ffffff",
                },
            },
        ]
    },
}

그리고 선언한 theme 이름을 사용하면 해당 theme가 적용된다.
위의 경우 bluesky 가 theme 이름이다.

 

DaisyUI는 어느 정도 편하게 Theme를 작성할 수 있도록 Theme Generator를 제공하고 있다.
https://daisyui.com/theme-generator/

 

기본적인 색상은 해당 generator 페이지에서 작성하면서 미리 보기를 하면 되고 글꼴, rounded 처리나 좀 더 세세한 custom 설정은 DaisyUI의 themes.js를 참고하여 설정하면 된다.

반응형
profile

파란하늘의 지식창고

@Bluesky_

내용이 유익했다면 광고 배너를 클릭 해주세요