Mathieu
Mathieu

Reputation: 5695

how to reset web components over specified style with `all: initial`?

I’m building a widget that is aimed to be embedded on other websites. I’d like to avoid using iframe so I was looking at all: initial. “This keyword specifies that all property values set on the element all is set on — or inherited from the element's parent” seemed to be perfect but I’m having an issue when previous rules have a greater specificity.

here is an example of the issue:

/* external css */
#color {
  color: red;
}

span {
  text-decoration: underline;
}

span {
  font-weight: bold !important;
}

/* my widget css */
/* reset */

widget,
widget * {
  all: initial;
}

/* then my widget style */
widget span {
  color: blue
}
<div id="div">
  Lorem <span id="color">ipsum</span> dolor sit amet,
  <widget>consectetur <span id="color">adipiscing</span> elit.</widget>
  Phasellus eget velit sagittis.
</div>

At this point the only style inside the widget should be the word “adipiscing” printed in blue the text-decoration has as intended be cleared but it’s still red and bold

I’ve tried prefixing the rules with ids it kinda work, but not for the !important rule. I also tried to add !important in some or each of the widget rules but it only makes things worst

Is there a way to make this work without touching at the external css?

Upvotes: 0

Views: 251

Answers (1)

Bram G
Bram G

Reputation: 183

Give your elements higher specificity paired with !important.

/* external css */
#color {
  color: red;
}

span {
  text-decoration: underline;
}

span {
  font-weight: bold !important;
}

/* my widget css */
/* reset */

widget,
widget * {
  all: initial;
}

/* then my widget style */
widget span {
    font-weight: initial !important;
}

widget span#color {
     color: blue;
}
<div id="div">
  Lorem <span id="color">ipsum</span> dolor sit amet,
  <widget>consectetur <span id="color">adipiscing</span> elit.</widget>
  Phasellus eget velit sagittis.
</div>

Upvotes: 1

Related Questions