Ant-design: Global CSS included with component CSS import

Created on 21 Dec 2016  ·  89Comments  ·  Source: ant-design/ant-design

Thanks for this great library!

I tried to use babel-plugin-import to do modular CSS imports, but along with the css for an individual component, there is a lot of global css being imported that interferes with my existing styles. Is it possible to import the CSS for an individual component without global CSS being included?

Thanks!

🗣 Discussion 🙅🏻‍♀️ WON'T RESOLVE

Most helpful comment

That's terrible design though.

All 89 comments

Do you mean CSS rules like this?

html,
body {
  ...
}

Yes.

It's impossible not to import those CSS rules now.

https://github.com/ant-design/ant-design/issues/1966#issuecomment-247946641

You have to override these global styles now.


Or you drop the style option of babel-plugin-import, import the less files indenpently.

@import "~antd/lib/style/themes/default.less";
@import "~antd/lib/button/style/index.less";

That's terrible design though.

This issue makes this library very difficult to work with. Especially having global properties on body etc. I think this issue should be made much more clear unless you have plans to change this.

@Forestdev @peitalin it's an known issue, but we don't have enough time to solve this issue.

But we can keep discussing here.

If we can import breaking changes, we can solve this issue. Such as, move styles in reset to components' styles:

Move:

* {
  box-sizing: border-box;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0); //  remove tap highlight color for mobile safari
}

To:

.ant-btn,
.ant-btn * {
  box-sizing: border-box;
  -webkit-tap-highlight-color: rgba(0, 0, 0, 0); //  remove tap highlight color for mobile safari
}

And for backward compatibility, we can provide a standalone reset stylesheet.

import 'antd/styles/reset.less'

is there any update on this?

We can discuss, but we have no time to apply any solution(if we can find) now.

I think this is a critical issue as not many people can afford importing a global css and having their existing styles overridden

That is really annoying which stopped me from adopting Antd

This will block many developers#

because ant can not compatible bootstarp,i had to give up using ant.

how about put out of less file into an independent library.

btw. I am trying

Hey guys, I am working on [email protected] and try to find a solution for global styles issue.

I tried the solution of import 'antd/styles/reset.less' from @benjycui. It turns out it would be a break change and make importing styles much more complicated, especially with babel-plugin-import. So I decide to pass it.

Then I find the main point of this issue is about babel-plugin-import which will turn code into:

import Button from 'antd/lib/button';
import 'antd/lib/button/style/css';   // It will import reset styles and hard to override it because it was imported lately!!!

The better workaround for this is not using style option of babel-plugin-import and import style manually.

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

// your global styles
body {
 ...
}

So I give up the whole reset.less idea and just remove the annoying reset codes like: https://github.com/ant-design/ant-design/blob/afce275d25abe958b32cf15ba1f16c49f4fca900/components/style/core/base.less#L33-L50

Also I added better typography code from bootstrap@v4 to resolve #6162

All updates are in #7682 now and will be merged into antd-3.0 soon.

Just change import 'antd/styles/reset.less to import 'antd/styles/typography.less.

When users upgrade from [email protected] , import 'antd/styles/typography.less is an adapter to make the migration easy.

When users who are new to antd, import 'antd/styles/typography.less is an optional feature, so they don't need to worry about conflicts.

Added antd/style/v2-compatible-reset.less.

+// For 2.x reset compatibility
+//   import 'antd/style/v2-compatible-reset';
+//     or
+//   @import '~antd/style/v2-compatible-reset.css';

Can somebody please explain some steps to fix this issue as this issue is closed now. I am trying to use antd in a chrome extension's content script and it messes up with all the webpages.

@abhinavzspace you can install antd@next to get the 3.0 Alpha build, which resolves this issue somewhat but not fully.

After a lot of time i found some solution that worked for me. Maybe it works for others...

Problem is each component imports a bunch of global resets and overrides (including normalize.css) from style/core/base.less , if this styles load asynchronous they override the page styles messing up everything.

Found that adding

import 'antd/lib/style/index.css'
// import 'antd/lib/style'  if you are using LESS

to the entry point of my project makes webpack pack the resets before all the other styles, so when an async component loads it doesnt import/include the resets again.

does it should give another index.less for each component. the index.less can be controlled. and also almost all less file remove @importdirective or just use @import (reference)

Will it be a good solution?

tsk tsk tsk. This issue should be "Open" so that everyone knows that this is a known issue. Just ditched antd in the middle of a project just for this.

This is a real bummer. Ant was recommended to me and it looks promising, but this behavior messes up our existing design and makes Ant feel like Bootstrap. 😦

Ant should be opinionated about the appearance of its own components, but not the appearance of the user's site.

This issue implies that Ant 3 fixes this issue. But I'm still seeing lots of global styles. What should users do to avoid adding those global styles?

@openjck I found that this seems to reset the global styles (I added it to my React entry point):

import 'antd/lib/style/v2-compatible-reset';

Found it buried in their changelog

I found that note, but it didn't work for me. The documentation is pretty sparse. What other style-related imports did you do, and in which order?

As far as Ant styles, that's about it. I am using the style: true setting too, which might matter.

What kind of global style changes are you seeing?

I'm using React with webpacker and rails and having the same problem before. To solve that, in my HTML view, I add stylesheet link tag of the existing CSS file name under the stylesheet_pack_tag, and that works.
= javascript_pack_tag 'root'
= stylesheet_pack_tag 'root'
= stylesheet_link_tag 'application'

@jhdavids8, where are you setting style: true? I'm not sure that applies to my setup.

I'm using create-react-app. The documentation recommends adding this to one of the main stylesheets:

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

...but doing so introduces global style changes, like a font-family and line-height that are set on the body.

I'm just using babel-plugin-import as documented here to import styles on demand. The style: true option is a way to import the Sass source files (see this), which we need as we also customize the Ant theme heavily

Our team just abandoned antd because of the global styles 😭 . I know you're busy but if you could find a way to solve this it would radically increase antd's reach.

Please reopen this issue. I'm still seeing this behavior and so are others.

+1

+1

自己添加的全局css,每次都会被打包在/lib/style/index.css的中间位置,我现在只是想去掉antd的
Add the correct display in IE 10-.
后面的
html,
body {
width: 100%;
height: 100%;
}
为什么就这么难呢……自定义的全局css为啥不能放在/lib/style/index.css 的尾部

+1

+1

I found I was able to resolve the issue in a way @afc163 described.

Typically you would do import 'antd/lib/tabs/style/css';, which points to a file with just this in it:

'use strict';
require('../../style/index.css');
require('./index.css');

I wanted to just import the Tabs CSS, so I added this to my component file:

import 'antd/lib/tabs/style/index.css';

And it appeared to style my Tabs component appropriately without affecting the rest of the page.

Be careful, however, since the first style is there for a reason - perhaps some antd components depend on it more than others and this may not work in all cases.

_If you're not already doing so, be sure to remove the style property from your .babelrc plugins:
[ "import", { "libraryName": "antd" } ]_

Hope that helps someone!

This is absolutely crazy.... A "modular" component library, that interferes with global styles. I have no idea why this library is so highly regarded with it gets such a fundamental thing wrong. Not to mention that they've closed this ticket as though the issue is resolved.

@strongui babel-plugin-import doesn't work for you ?

@abenhamdine No it does not. And I'm not alone judging by the comments above.

Using latest version of library , I'm still having this issue.

Did anyone find a fix (ideally not a reset) ?

I have had success with importing the exact CSS for the smaller components I need

import 'antd/lib/checkbox/style/index.css'

But now i'm trying to implement a table. The Table relies on many styles, so i've had to import all of the various CSS sheets separately, which is fine. _Except_ that for the sorting feature I need the icon CSS, which does not exist within antd/lib/icon. Instead I've had to import the main style sheet since the icon css just redirect to it.

import 'antd/lib/style/index.css'

This is the file that affect the rest of my app ☝️

At the very least, can you make it so that no CSS sheets redirect to the main one? (Like the icon one that I need for table sorting?)

Also, @afc163 please reopen this issue, it has not been solved.

Just read through the thread and see the "WON'T FIX" tag. This is an P0 bug that blocks every large application, embedded component that chooses Ant.D to become their component lib. The tag should be 'HEART BREAKING'.

@afc163 why in the world is this marked as won't fix?? The core of the react philosophy and modular design is for components NOT to bleed into other components. This makes absolutely no sense. I've spent some time and extracted the css for the tree-select and been able to make it work without impacting anything else, so I know it's possible.

+1 for reopening this issue. Trying to transition our app from Material-UI to AntD and this is a major barrier to entry.

+1 for reopening. babel-plugin-import doesn't work for me, tried all the tuts and instructions. Not able to change the global font for my app 😱

There was a related issue in blueprintjs palantir/blueprint#244.

One suggestion is using a postcss plugin called: css-byebye
https://github.com/AoDev/css-byebye

This may help as a temporary solution.

Great library but horrible way to treat it's users. Why should the default fonts be changed? And why is there no way to reset the fonts and styling?

This is keeping us - and many others judging from reading comments - from using this library.

I don't know if this is a language/cultural issues, but developers of this library - take note: What is the point of making a library that no one wants to use? Why are you making it difficult for your fellow developers to use your library?

What is the point of making a library that no one wants to use? Why are you making it difficult for your fellow developers to use your library?

Please keep it moderate.
Many developers and startups use or want to use this library.

This library is open-source and free. If you don't want to use it, don't use it.
If you want to modify it, you can fork it for your own use or submit a PR, maintainers of ant-design are open to contributions.

So there's no need to rant here.

This issue is also a deal-breaker for my team.
We love the project, and all the work that was done, but this single issue prevents us from using it.

That's why I'm still following this issue in the hope it's reopened an fixed in the near future.

Oh I am very moderate. And I am not ranting here.

I am bringing to your attention that your library - even though it is great - shouldn't have unnecessary side-effects. Imagine if I use MomentJS (for example) and it starts displaying dates and times in Klingon!

"Go fork yourself" is also not the answer. In fact that is the sad and pathetic state of many open-source projects.

We are building complex systems ourselves - we are not rookies here. We want to use a library and get on with our lives. At least there should be a way to ask the library not to change the default font or font size. That is all I - and may others here - are asking.

You can choose to be tone-deaf and ignore these concerns - concentrating instead of the choice of my words - OR you can choose to understand what people here are saying and provide a way for them to use your library without any side-effects.

May the force be with you while you live long and prosper.

Couldn't agree more with @kotpal . What'a amazes me that this discussion isn't about "can you add this feature" or "wouldn't it be nice if...", it's literally trying to convince an author that a component should not be messing with the global state. It's literally point blank the core concept of ReactJS and any modular design.

You DO NOT mess with GLOBAL anything, unless you are providing a global theme or something.

I get what @abenhamdine is saying. But I also agree with @strongui .

Maybe Ant is supposed to be a whole experience. But in practice many people still need to work with legacy code that they just can't change it. And if this project clashes with that old code we lose all the benefits of using React (or any other framework like it) in the first place.

If this issue is stopping so many people from fully adopting the project maybe we can pull together and put a bounty on it or something?

I know that I don't have the knowledge or time to fix this issue on my own, so what would it take for the contributors to fix it ? (and yes it is an issue and not a feature)

I have had some success with overriding the global css provided by antd and using projects like styled jsx.
You can see the site deployed here! Ps: its work in progress.

I've just found myself in the same situation, and have been having moderate success using the same approach described by @inverts and @corinnebrady (https://github.com/ant-design/ant-design/issues/4331#issuecomment-361421192 and https://github.com/ant-design/ant-design/issues/4331#issuecomment-365481037). So, some of my components look like this:

// ...
import Modal from 'antd/lib/modal'
import 'antd/lib/modal/style/index.css'

import AutoComplete from 'antd/lib/auto-complete'
import 'antd/lib/auto-complete/style/index.css'

import Form from 'antd/lib/form'
import 'antd/lib/form/style/index.css'
import 'antd/lib/select/style/index.css'

import Button from 'antd/lib/button'
import 'antd/lib/button/style/index.css'
// ... etc

This works somewhat OK with most antd components, but there are others that don't have a specific css file associated to them, and it's styles can only be found in the global one. This is the case for the icon component, to make them work I had to manually copy all the icon related styles from the global file to my own stylesheet. Maintainers: would you accept a PR to include an antd/lib/icon/style/index.css?

Seems like you can include individual less files too, e.g import 'antd/lib/spin/style/index.less'

Any plans to resolve this issue officially?

Still a problem but I'm trying to fix with referenced imports like @reyronald explains.

I'm stucked too with Icon's style problem.

@reyronald can you make a PR, please?

People who are suffering from this might wanna try my fork by adding the package directly from the repository

yarn add github:serguzest/ant-design#3.4.1-NoCssPollution

or

npm install github:serguzest/ant-design#3.4.1-NoCssPollution

I only ruled out base.less and built it without any other modifications. It works in my case, I don't use many components from it. It will probably break look of some components especially if you don't already have sane reset stylesheet in your project. #4546

Hey @afc163 I'd also like to hop in here and add additional voice for a fix to this issue. We build a large application with many targets, and a few of our targets are loaded on 3rd party sites. antd interfering with global CSS is problematic for us because we end up blowing away CSS resets and fonts for those 3rd party sites. We love the library and would love to contribute to a fix if maintainers were willing to point us in a direction. Please re-open or direct the conversation to another open issue! Thanks

So we were able to get this working (at least so far) by using some webpack manipulation to load an alternate less file:

new webpack.NormalModuleReplacementPlugin( /node_modules\/antd\/lib\/style\/index\.less/, path.resolve(rootDir, 'src/styles.less') ),

Where the src/style.less file loads the same files as the index.less file, but loads them within the scope of a top-level selector:

#root { @import '~antd/lib/style/core/index.less'; @import '~antd/lib/style/themes/default.less'; }

The result is that all of the "global" styles are being applied with the #root scope:

`#root article,

root aside,

root dialog,

root figcaption,

root figure,

root footer,

root header,

root hgroup,

root main,

root nav,

root section {

display: block;
}
`
etc...

Hope this is helpful for someone.

Folks, it's really annoying. This styling behavior it's not you would expect from world class UI library.

At least mention about the global reset in docs, so people do not get confused. Or probably some guide "Integrating in legacy website" with recipe about importing individual styles and icons will be helpful

I think the maintainers have unsubscribed from this issue after it was closed because they haven't participated in the discussion since, so we will probably not receive any official support on this unless we open a new issue, ping them directly or open a PR.

I finally found a way to circumvent this problem by producing a new CSS file based on the original antd.css, with every rule prefixed with a custom class. My solution uses PostCSS, Gulp and postcss-prefixwrap plugin:

https://gist.github.com/sbusch/a90eafaf5a5b61c6d6172da6ff76ddaa

It is far from perfect, but works surprisingly well. At least for my needs ;-)

The gist also contains a ready-made version of antd CSS, prefixed with .antd-ns ("ns" as shorthand for "namespace")

Notes:
An important requirement for me was that it's automated, so prefixed CSS can easily be produced for every new ant release.

  • it's intended just as a tool for creating the prefixed CSS; so it could run from different folder separated from your project. No need for your antd-based project to include PostCSS or Gulp! The resulting CSS just needs to be placed in static CSS folder of your project (which is done by Gulp if configured accordingly).
  • postcss-prefixwrap must be at least version 1.3.0, which includes my patch to preserve antd keyframe animations

Comments / feedback always appreciated!

Thanks to @dbtedman for making this possible with his fine PostCSS postcss-prefixwrap plugin.

Comments / feedback appreciated!

I finally found a way to circumvent this problem by producing a new CSS file based on the original antd.css, with every rule prefixed with a custom class.

This is IMHO the straigthest solution.
Personnaly, I have no need currently for this, but it would be beneficial for everyone if somebody would submit a PR to add a classname less variable (eg .@{scope}) before each css rule in less files.

By default, this variable would be empty, to avoid breaking current behaviour.

One would only have to set the variable with, for instance, antd to isolate the styles.

I think this solution would be acceptable for maintainers and would allow to go forward.

Here is a workaround which worked for me. I created styles.less file

// Doing what antd/lib/style/core/index.less does
// but without loading "base" which overwrites global styles
@import '~antd/lib/style/mixins/index.less';
@import '~antd/lib/style/core/iconfont.less';
@import '~antd/lib/style/core/motion.less';

@import '~antd/lib/menu/style/index.less';
@import '~antd/lib/dropdown/style/index.less';
@import '~antd/lib/button/style/index.less';
@import '~antd/lib/checkbox/style/index.less';
@import '~antd/lib/grid/style/index.less';

In .babelrc I have:

  "plugins": [
    [
      "import",
      {
        "libraryName": "antd",
        "style": false,
      }
    ]
  ]

for optimizing JS build size as described in https://ant.design/docs/react/getting-started#Import-on-Demand and https://github.com/ant-design/babel-plugin-import

For customized styling I changed my webpack config to:

module: {
  rules: [{
    test: /\.less$/,
    use: [{
      loader: 'style-loader'
    }, {
      loader: 'css-loader'
    }, {
      loader: 'less-loader',
      options: {
        javascriptEnabled: true,
        modifyVars: {"primary-color": "#ed1c24"},
      }
    }]
  }]
}

as described in https://ant.design/docs/react/customize-theme#1)-Using-theme-property-(recommended-way)

BTW: I tried using new webpack.IgnorePlugin(/style\/core\/base/) to just ignore this "base.less" file from processing but I couldn't make it work. I don't know why. My hypothesis is that because it is processed with LESS, and not with Webpack directly.

For what its worth, I manually edited antd.css and was able to remove unwanted styling without breaking any antd components that I use.

@paneq I'm currently doing the same. Note that babel-plugin-import's style option could also be a function, which can decide if a style should be included. I just didn't get it to work. Would have to debug that …
Maybe I'm also misinterpreting that option?

@paneq I've copied what you've done and it seems to be worked so far, but I haven't tried enough components to see which ones require that global css. Thanks

@vthinkxie

hi, it should be possible to try match all elems, starting with .ant, and assign them styles

*[class^='ant-']{
box-sizing: border-box;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0); // remove tap highlight color for mobile safari
}

It should have crossbrowser compatibility and shouldn't take long to implement.

So we were able to get this working (at least so far) by using some webpack manipulation to load an alternate less file:

new webpack.NormalModuleReplacementPlugin( /node_modules\/antd\/lib\/style\/index\.less/, path.resolve(rootDir, 'src/styles.less') ),

Where the src/style.less file loads the same files as the index.less file, but loads them within the scope of a top-level selector:

#root { @import '~antd/lib/style/core/index.less'; @import '~antd/lib/style/themes/default.less'; }

The result is that all of the "global" styles are being applied with the #root scope:

Which version of less-loader are you using? Seems like it only works with 3.0.0? See. e.g. https://github.com/webpack-contrib/less-loader/issues/184

Also, which version of antd were you using for this workaround? The reason I'm asking is that I didn't have success even with [email protected] and [email protected] (webpack had problems resolving after the change). ..

I don't know if this helps anyone, but the following helped me import the CSS for only the component in use:

import Modal from 'antd/lib/modal'
import 'antd/lib/modal/style/css'

I don't know if this helps anyone, but the following helped me import the CSS for only the component in use:

import Modal from 'antd/lib/modal'
import 'antd/lib/modal/style/css'

Yeah, this seems to work ok for many components. Your milage may vary, though -- at least Select needs a little more than just the component's own styles. The "remove" icon in selections won't render otherwise; I didn't have time to track down the issue completely, but i's probably something minor. So you may need to mimic some styles from the main styles in some of the components.

While this option is not quite perfect, it could work well for many components. The custom styles are in risk of breaking with updates, but you can obviously control when you want to do your updates.

The best solution I found for our organization is to include the entire CSS sheet from antd, with any styles that affect non antd named styles stripped out. Mileage might vary, and there is obviously the downside of _every_ style now being imported. But it works well and I haven't seen any issues after doing so for about two months now.

@jaleikas
Have you found a workaround on this? As far as I can tell, the issue with [email protected] is still not resolved and therefore the suggested fix with NormalModuleReplacementPlugin does not work. That solution actually seems like the best one since things can be manually overridden and scoped.
I tried the same thing as you, downgrading the less-loader, but then webpack resolve does not work.

Using [email protected] here.

Las personas que sufren de esto pueden querer probar mi fork agregando el paquete directamente desde el repositorio

yarn add github:serguzest/ant-design#3.4.1-NoCssPollution

o

npm install github:serguzest/ant-design#3.4.1-NoCssPollution

Solo descarté la base y la construí sin ninguna otra modificación. Funciona en mi caso, no uso muchos componentes de él. Probablemente se verá afectado por algunos componentes, especialmente si aún no tiene una hoja de estilo de restablecimiento razonable en su proyecto. # 4546

this works for me

People who are suffering from this might wanna try my fork by adding the package directly from the repository

yarn add github:serguzest/ant-design#3.4.1-NoCssPollution

or

npm install github:serguzest/ant-design#3.4.1-NoCssPollution

I only ruled out base.less and built it without any other modifications. It works in my case, I don't use many components from it. It will probably break look of some components especially if you don't already have sane reset stylesheet in your project. #4546

Thank you for this solution!

Have you found a workaround on this? As far as I can tell, the issue with [email protected] is still not resolved and therefore the suggested fix with NormalModuleReplacementPlugin does not work. That solution actually seems like the best one since things can be manually overridden and scoped.

I chose to stop using antd, and decided to pick some unstyled components (like rc-switch). The problem is that most of the "unstyled" components are either horribly/not documented, and some of them also seem to behave differently, so for the most part, I gave up and looked elsewhere...

hi, it should be possible to try match all elems, starting with .ant, and assign them styles

*[class^='ant-']{
box-sizing: border-box;
-webkit-tap-highlight-color: rgba(0, 0, 0, 0); // remove tap highlight color for mobile safari
}

It should have crossbrowser compatibility and shouldn't take long to implement.

@tylik1 , thank you! i just needed to fix the font-family to match the rest of my electron app. this totally saved me.

I don't know if this helps anyone, but the following helped me import the CSS for only the component in use:

import Modal from 'antd/lib/modal'
import 'antd/lib/modal/style/css'

it work for me by the following.

import Icon from 'antd/lib/icon';
import 'antd/lib/icon/style/index.css';

Unfortunately this is a show stopper. I will also not implement Antd even though the date picker is the best I could find so far.

We are currently searching for a react component library for our company and this is also a blocking issue for us, and we probably an not use ant because of it.

We are also looking at react MUI, which has great theming options, maybe you can have a look at how they do it and implement something similar.

I used https://www.npmjs.com/package/patch-package to comment out

// import 'normalize.css/normalize.css';

from antd-mobile/es/style/index.js.
My purpose was to get next.js to build, so in my case I just included a CND link in my header instead.

It was 2020, humanity died out, coronavirus, ant-design adds global styles to the project...

Tracking in #9363

Was this page helpful?
0 / 5 - 0 ratings

Related issues

AhmedSayed77 picture AhmedSayed77  ·  3Comments

taikongfeizhu picture taikongfeizhu  ·  3Comments

tangsj picture tangsj  ·  3Comments

plandem picture plandem  ·  3Comments

drcmda picture drcmda  ·  3Comments