nikhil kekan
nikhil kekan

Reputation: 532

How to not let parent css impact css of a child component?

I have created a react app, which is basically a widget that can be included on any HTML page, however when mounted on different pages, its CSS is getting affected. I want the CSS of this react app to be solid and not affected by its parent page's CSS. I have index.scss which has font-family etc. defined for body and code. Everywhere else I have used styled components to create custom components with their respective CSS properties. I want to know if it's possible that my styled component's CSS is getting overridden. Can CSS modules resolve my problem?

Upvotes: 3

Views: 4228

Answers (2)

Tammy Shipps
Tammy Shipps

Reputation: 945

I would use pseudo-namespacing to differentiate contexts. I would not use !important unless as a last resort because a) you don't need it at all, and b) it makes overwriting the overwrite that much harder.

<div id="aboutUs" class="foo">
  <span class="bar"></span>
</div>
.foo {
  /* Default styles */
}
#aboutUs.foo {
  /* Override defaults */
}
#aboutUs .bar {
  /* Override defaults */
}

I suggest checking out how cascading works: https://developer.mozilla.org/en-US/docs/Web/CSS/Cascade

Upvotes: 1

dobson
dobson

Reputation: 466

1: Normalize your styling

For example if you have a <div> that is having it's position modified by styling on a page, you can manually set that position to what it should be on said <div> so that it doesn't rely on inheritance.

For example:

/* Global styling that will affect '.my-app div' */
div {
  display: flex;
}

/* Override global styling by manually setting display, instead of relying on it's supposed default value */
.my-app div {
  display: block;
}

2. Use !important

Add the !important tag to your styles so that they are prioritized.

.my-class {
  display: flex !important;
}

Upvotes: 0

Related Questions