Tom
Tom

Reputation: 1618

CSS Combine Class & Style

I have a table row which has a class applied to it. Depending on a value set in that row I may change the background color using a style directly within the row.

$bground = ($a === 'a') ? '#A0A0A0' : '#ffffff';

<tr class='$class' align='center' style='background-color:$bground '>

Adding the style stops other css that is applied to the page from working. eg: the following stop working.

.res table tr:hover {
    background-color: #808080;
}

.res table tr.selected {
    background-color: #808080;
}

if I remove style='background-color:$bground '> from the row then the hover and select as expected.

Any way to do this ?

Thanks

Upvotes: 0

Views: 2643

Answers (2)

treyBake
treyBake

Reputation: 6560

firstly background-color can be shortened to background like so: .className {background: #fff}

next, you can combine dupe stylings like so:

.classOne, .classTwo, #idOne {background: #fff;}

next, don't assign any inline js or css. It's bad practice that leads to harder to maintain code. Just add a new id/class onto it instead.

lastly, the reason that assigning inline css stops the stylesheet is because inline css has a higher specificity value. In your stylesheet you can use elements to add to the weight:

div.classOne.someOtherClassItHas {background: #fff;}

and if that doesn't bump it up enough you can always add the !important rule which helps stop overrides:

.class {background: #fff !important;}

though use this sparingly and as a last resort (I recommend moving any !important rule to the bottom of the stylesheet) as it can mess with the behaviour of the stylesheet.

Upvotes: 4

sorayadragon
sorayadragon

Reputation: 1087

No. Inline styles always override CSS. Since you have set the background color via an inline style, you cannot change it with CSS.

A solution to this problem is instead of changing the background color with an inline style, you just add another class to the tr which has a different rule for the background color.

.res table tr.color1 {
background-color: #A0A0A0;
}

.res table tr.color2 {
background-color: #ffffff;
}

Then in your code, add the class to the tr:

$bgroundClass = ($a === 'a') ? 'color1' : 'color2';

<tr class='$class $bgroundClass' align='center'>

Upvotes: 2

Related Questions