Tailwinds + Ant design : Button color is white but has own color wnen I hover it
Asked Answered
L

6

13

I applied the tailwind CSS and Ant design with my Next.js project.

I found the primary button got a white color.

enter image description here

But it shows own primary button color when the mouse over.

enter image description here

global.css

@tailwind base;
@tailwind components;
@tailwind utilities;


@layer base {
    h1 {
      @apply text-2xl;
    }
    h2 {
      @apply text-xl;
    }

    /* ... */
  }


@import '~antd/dist/antd.css';

Home.module.css

.container {
  padding: 0 2rem;
}

.main {
  min-height: 100vh;
  padding: 4rem 0;
  flex: 1;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}

.footer {
  display: flex;
  flex: 1;
  padding: 2rem 0;
  border-top: 1px solid #eaeaea;
  justify-content: center;
  align-items: center;
}



.footer a {
  display: flex;
  justify-content: center;
  align-items: center;
  flex-grow: 1;
}

.title a {
  color: #0070f3;
  text-decoration: none;
}

.title a:hover,
.title a:focus,
.title a:active {
  text-decoration: underline;
}

.title {
  margin: 0;
  line-height: 1.15;
  font-size: 4rem;
}

.title,
.description {
  text-align: center;
}

.description {
  margin: 4rem 0;
  line-height: 1.5;
  font-size: 1.5rem;
}

.code {
  background: #fafafa;
  border-radius: 5px;
  padding: 0.75rem;
  font-size: 1.1rem;
  font-family: Menlo, Monaco, Lucida Console, Liberation Mono, DejaVu Sans Mono,
    Bitstream Vera Sans Mono, Courier New, monospace;
}

.grid {
  display: flex;
  align-items: center;
  justify-content: center;
  flex-wrap: wrap;
  max-width: 800px;
}

.card {
  margin: 1rem;
  padding: 1.5rem;
  text-align: left;
  color: inherit;
  text-decoration: none;
  border: 1px solid #eaeaea;
  border-radius: 10px;
  transition: color 0.15s ease, border-color 0.15s ease;
  max-width: 300px;
}

.card:hover,
.card:focus,
.card:active {
  color: #0070f3;
  border-color: #0070f3;
}

.card h2 {
  margin: 0 0 1rem 0;
  font-size: 1.5rem;
}

.card p {
  margin: 0;
  font-size: 1.25rem;
  line-height: 1.5;
}

.logo {
  height: 1em;
  margin-left: 0.5rem;
}

@media (max-width: 600px) {
  .grid {
    width: 100%;
    flex-direction: column;
  }
}

JSX code is like the following.

import * as React from "react";
import { Button, Table } from "antd";
import FishbowlLayout from "../../components/FishbowlLayout";

export function Index() {
  

  return (
    <div>
      # FishbowlLayout uses Layout from Ant design.
      <FishbowlLayout>. 
        <div className="grid grid-cols-6 gap-4">

          # Button
          <Button className="col-end-6 col-span-1 ..." type="primary">
            New project
          </Button>

          # Table
          <div className="col-span-5 ">
            <Table dataSource={dataSource} columns={columns} />;
          </div>
        </div>


      </FishbowlLayout>
    </div>
  );
}

export default Index;
Leija answered 2/4, 2022 at 5:45 Comment(3)
Can you share the react code where you're inserting this button component in your page?Truthful
I added my JSX code too.Leija
You can simply use tailwind components from taiblocks tailblocks.cc or from flowbite flowbite.com/docs/components/buttonsGassaway
T
21

In your tailwind.config file add the following:

corePlugins: {
    preflight: false
}

it's explained in a lot more detail in this video: https://www.youtube.com/watch?v=oG6XPy1t1KA&ab_channel=TailwindLabs

edit: typo, thanks for pointing it out Fabio

Thorstein answered 16/5, 2022 at 21:53 Comment(4)
You should not use camelCase: preflight: false and it works fine. Thank you for the tipRawley
It will not work if you upgrade an existing projectHegumen
Thanks. It worked for me but it doesn't affect other things?Parbuckle
It may help for new projects. But it breaks some default styles of tailwind. And if you implement it on ongoing project you should check all you components.Fiberglass
S
7

I also encounter the question recently, after deeper investigation, I think it is better resolve by postcss plugin, So I created the plugin postcss-antd-fixed.

It will add excluded pseudo class for button related selectors now from tailwind preflight.css

For example, Transform the code

button,
[type='button'],
[type='reset'],
[type='submit'] {
  -webkit-appearance: button;
  background-color: transparent;
  background-image: none;
}

to

button:where(:not([class^="ant"])),
[type='button']:where(:not([class^="ant"])),
[type='reset']:where(:not([class^="ant"])),
[type='submit']:where(:not( [class^="ant"])) {
    -webkit-appearance: button;
    background-color: transparent;
    background-image: none;
}

Online example: https://stackblitz.com/edit/postcss-antd-fixes?file=postcss.config.js

It make antd + tailwindcss works smoothly, at least for me.

Moreover, the plugin support custom prefixCls and hashPriority, check out type definition about PluginCreator<{ prefixes?: (string | PrefixItem)[] }>

Succor answered 21/8, 2023 at 12:58 Comment(1)
My "Ok" button background for date picker from ant-design was transparent because of tailwind base styling; your plugin solved this issue. Thank you so muchDamondamour
W
3

Interesting. Preflight is a set of base styles that Tailwind applies, and it is setting the button background color to transparent.

The solution is to disable Preflight in tailwind.config.js; see the Tailwind documentation.

Wheelman answered 9/7, 2022 at 7:10 Comment(0)
G
1

A simple solution would be to override the CSS as shown below:

.ant-btn:not([disabled]):hover {
    background:#faad14 !important;
}
Glassblowing answered 4/4, 2022 at 12:17 Comment(0)
A
0

One CLS-related (Cumulative Layout Shift) thing also resolves the transparent button issue;

(code below is originally taken from the linked solution, but was then changed a little)

Store this component as separate file.

'use client';
import { type PropsWithChildren, useState } from 'react';
import { useServerInsertedHTML } from 'next/navigation';
import { createCache, extractStyle, StyleProvider } from '@ant-design/cssinjs';

export const AntdRootStyleRegistry = ({ children }: PropsWithChildren) => {
  const [cache] = useState(() => createCache());

  useServerInsertedHTML(() => {
    return (
      <script
        dangerouslySetInnerHTML={{
          __html: `</script>${extractStyle(cache)}<script>`,
        }}
      />
    );
  });

  return (
    <StyleProvider cache={cache} ssrInline hashPriority={'high'}>
      {children}
    </StyleProvider>
  );
};

And then put the component under your antd's ConfigProvider. I also use a separate file for it:

import { type PropsWithChildren } from 'react';
import { ConfigProvider } from 'antd';
import { antdThemeConfig } from '@/app/antdThemeConfig'; // it's where you store your Antd theme config
import { AntdRootStyleRegistry } from '@/app/[locale]/AntdRootStyle';

export function AntdProviders({ children }: PropsWithChildren) {
  // see https://mcmap.net/q/903780/-next-js-13-with-ant-design-5-components-and-pages-render-before-styles-load-causing-jump
  return (
    <ConfigProvider theme={antdThemeConfig}>
      <AntdRootStyleRegistry>{children}</AntdRootStyleRegistry>
    </ConfigProvider>
  );
}

This provider should wrap your entire antd application.

Aretino answered 12/9, 2023 at 5:39 Comment(0)
R
0

Short term solution: For example: I am using antd primary button on my code like:

<Button type="primary">Click me</Button>

Now go to your main/root css file (globals.css in my case) and add:

.ant-btn-primary:not([disabled]) {
  background:#1677ff !important;
}
.ant-btn-primary:not([disabled]):hover {
  background:#1f4ce0 !important;
}

The button color starts appearing. Note: to get classNames, kindly go to antd official button docs and hover on button you want and grab it. Each button type has unique className like antd-btn-dangerous and antd-btn-primary. I faced same issue and the correct answer choosen by you that uses preflight: false has too much risk. I tried that and my whole codebase styling fusked up badly that i had to revert it. Happy Coding!

Renarenado answered 17/1 at 18:44 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.