I have 2 css classes that hold the background-color property. One class is for general elements and the other is for selected elements. I put the selected_element class on the element according to data i have in my model.
This is the css:
.selected_obj {
background-color: #00EE76
}
.general_obj{
/* Othe CSS Properties */
background-color: #d9d9d9;
}
This is my JSP:
<c:forEach items="${myModel.myCollection}" var="obj">
<c:choose>
<c:when test="${obj.id == myModel.selectedObj.id}">
<div class="selected_obj general_obj">
<span>${obj.name}</span>
</div>
</c:when>
<c:otherwise>
<div class="general_obj">
<span>${obj.name}</span>
</div>
</c:otherwise>
</c:choose>
</c:forEach>
When i view the generated HTML, i can see the selected_obj class on the correct elements but the value is overriden by the backgroung-color property value of the general_obj class. How is the correct value selected by the brouwser and how can i overcome this?
When two conflicting rules with the same specificity are to be applied, the latter one wins. ) In your case
.general_objbackground-color rule wins (= is actually applied), because it goes after the.specific_objrule in CSS file.This –
class="general_obj selected_obj"– change in HTML will do nothing to fix the problem, as both classes will still have the same specificity.One obvious approach to fix this problem is using
!important:… as styles specified with
!importantwill override the styles that otherwise should be applied (by following the general CSS cascading rules).That goes well as a quick fix, but I’d actually strongly suggest against it (the reasons are described in this article quite well; CSS-Tricks also have a mighty word on that topic).
Instead you may either…
make a specific multi-class rule for such cases, like this:
.selected_obj, .selected_obj.generic_obj {background-color: #00EE76;
}
(strongly suggested) fix the CSS file so that rules for generic classes are described first and rules for specific classes follow them.
Actually, it’s a great rule of thumb: deal with all the generic things first, then work with specialties. )