OpenStack
OpenStack

Reputation: 5596

How to apply CSS class without affecting global behvior

I am using a third party library which has its own CSS class. This is how the DOM looks:

<div id="toast-container" class="toast-custom" aria-live="polite" role="alert">
      <div class="toast toast-info" style="display: block;"> ....

This is the class I am overriding to fix the width

.toast-custom {
  top: 0;
  left: 30%;
  width: 50%;
}

This is the class already provided by framework

#toast-container > div {
  position: relative;
  pointer-events: auto;
  overflow: hidden;
  margin: 0 0 6px;
  padding: 15px 15px 15px 50px;
  width: 46%;
  -moz-border-radius: 3px 3px 3px 3px;
  -webkit-border-radius: 3px 3px 3px 3px;
  border-radius: 3px 3px 3px 3px;
  background-position: 15px center;
  background-repeat: no-repeat;
  -moz-box-shadow: 0 0 12px #999999;
  -webkit-box-shadow: 0 0 12px #999999;
  box-shadow: 0 0 12px #999999;
  color: #ffffff;
  opacity: 0.8;
  -ms-filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=80);
  filter: alpha(opacity=80);
}

I am not able to modify the width of the dix without touching #toast-container > div but if I make change to #toast-container > div it will have a global impact. How can I make use of .toast-custom to make the required change?

Upvotes: 1

Views: 64

Answers (1)

Steve G
Steve G

Reputation: 13377

The issue that you're having is that an # "ID selector" (eg. #my-rule) is more specific than a . "class selector" (eg. .my-rule), and the [last] most specific CSS selector (rule) wins.

This should work on any #toast-containers that implements .toast-custom:

/* Note "no space" between */
#toast-container.toast-custom > div {
  ...
}

This is basically saying "select the direct descendant div of #toast-containers elements that also have a .toast-custom class applied." Since that is more specific than the framework's rule, your rule will override, but only in that case. -- (#toast-containers that do not implement .toast-custom should not be affected.)

From MDN

Specificity is the means by which browsers decide which CSS property values are the most relevant to an element and, therefore, will be applied.

See CSS Specificity on MDN for more information.

Upvotes: 2

Related Questions