Pi_Tonix Pi_Tonix - 1 year ago 82
HTML Question

CSS forcing a div to follow class

So I have a div that follows a CSS script, in this script it's defined as the following:

#div { height: 30px; width: 30px; float:left;}

I need the divs properties, but for it to instead float to the right and plan to do so using a class:

.class {float: right}

However this doesn't work (it still float to the left).

Is there a way to force the div to follow the class over its own predetermined properties?

Answer Source

You have run into CSS specificity issue. An ID has higher specificity compared to a class so it's values cannot be overridden using just a class selector unless you plan to use !important to force the browser to select the class attribute value. A better solution would be use multi-selector syntax to target the div you want to style.

For example,

<p id="foo" class="bar">


#foo {   color: red; }
.bar {   color: green !important; } /* avoid */
#foo.bar {    color: yellow;    } /* multi selector*/

However, using !important has it's own set of problems.

See my jsfiddle link for how to use important.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download