Hi,

I have an elements:

<div id="mydiv" class="mydivclass">

</div>

In CSS i have like:

div#mydiv {
width: 100px;
}
div.mydivclass {
width: 200px;
}

What i want is to the second CSS (class) setting override the first (id) one. The thing is that the class is added dynamically and i want that element to be styled differently if the class is there, however, it is always styled using the id styling property.

Thanks

Dani AI

Generated

IDs have higher specificity than classes, so a class added at runtime will lose to an existing ID rule unless you change specificity or the cascade. As discovered, using !important forces the class rule to win, but that is a short-term fix and makes future maintenance harder.

Safer options (pick one that fits your constraints):

  • Move presentational rules off IDs and onto classes. Use a modifier pattern (BEM or similar) and keep IDs as JavaScript hooks only.
  • If you cannot change markup, use a selector that targets both the ID and the class (an ID+class compound selector) so its specificity is greater than the ID-only rule.
  • Use CSS custom properties: put the actual property value behind a var() in a less-specific rule, and have the dynamic class set the custom property to a different value.
  • If changing selectors is impossible, increase specificity by chaining selectors or placing the overriding stylesheet later in the cascade—only works when specificity is equal.

Quick troubleshooting checklist:

  • Inspect the element in DevTools and look at the computed style to see which rule and file are winning.
  • Search for any other !important or inline style attributes.
  • Verify the dynamic class is added to the same element that the styles target (not a child).
  • Confirm the CSS file with the override is loaded after the original rules.

References for exact behavior and edge cases: Specificity and Cascade.

Silly me, !important did the job (just posting if anyone else needs to know this).

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.