가끔 동적으로 색상을 변경하고 싶을때가 있습니다.
A 버튼을 누르면 빨강
B 버튼을 누르면 파란색으로
바꾸고 싶을때가 있죠
https://tailwindcss.com/docs/customizing-colors
Customizing Colors - Tailwind CSS
Customizing the default color palette for your project.
tailwindcss.com
tailwindcss 문서를 보다보면 custom color는
tailwind.config.js파일을 수정하면 된다고 합니다.
module.exports = {
theme: {
colors: {
transparent: 'transparent',
current: 'currentColor',
'white': '#ffffff',
'purple': '#3f3cbb',
'midnight': '#121063',
'metal': '#565584',
'tahiti': '#3ab7bf',
'silver': '#ecebff',
'bubble-gum': '#ff77e9',
'bermuda': '#78dcca',
},
},
}
이렇게 theme.color 안에 key-value 형태로 적어주면 됩니다.
배경을 빨강으로 바꾸고 싶을때 tailwindcss를 이용하면 이렇게 하곤 합니다.
<a class="bg-red">
그럼 동적으로 할땐 어떻게 할까요?
let color_name = "red"
<a class="bg-{color_name}">
이게 동작할까요?
네 동작합니다.
tailwindcss에서 미리 빌드된 기본 색상인 red는 동작을 합니다.
하지만 저희가 직접만든 색상 이름은 tailwind.config.js에 등록해도 동작되지 않습니다.
let color_name = "favorite_color"
<a class="bg-{color_name}">
이 방법은 동작되지 않습니다.
이유는 tailwindcss는 class를 통채로 입력받아서 반응하기 때문입니다.
tailwindcss가 클래스 이름을 추출할때 소스 파일에서 연속된 완전한 문자열만 찾기 때문에 이런일이 발생합니다.
그래서 이 코드를 동작하게 하려면 아래방법으로 해야합니다.
let color_name = "favorite_color"
let colors = {
'favorite_color':'bg-favorite_color'
}
<a class={₩${colors[color_name]}₩}>
헤더인 bg_까지 한번에 class에 등록해야 적용됩니다.
위와 비슷한 사례로 hex값을 이용한 색상은 아래처럼 적용해야합니다.
let color_name = "favorite_color"
let colors = {
'favorite_color':'bg-[#123456]'
}
<a class={₩${colors[color_name]}₩}>
'스터디 > Etc' 카테고리의 다른 글
[SEO] 사이트맵 - 사이트를 홍보하는 가장 기본적인 방법 (3) | 2024.01.04 |
---|---|
[Supabase] js query예제 모음, 에러 메세지 모음. (0) | 2023.12.21 |
[StatCounter] 전세계 화면 해상도 통계 및 개발시 사이즈 참고. (1) | 2023.12.02 |
CloudFlare Worker Cron Tip. (0) | 2023.11.28 |
[Tailwindcss] iOS Blur freezing 현상 (bug) (1) | 2023.11.24 |
댓글