roast_soul
roast_soul

Reputation: 3650

how to change CSS priority (don't use !important)

If the css is as below:

input[type="text"]
{
     border: 1px solid green; 
}

.text
{
     border: 1px solid red ; 
}

And if the html is as below:

<div>
 <input type="text" class="text"/>
</div>​

The border-color of the textbox is green. It seems that the "element" has the higher priority.
How to make the .class valid? Is it a must to use the !important?

Any other choices?


I tested below CSS code:

input[type="text"]
{
     border: 1px solid green; 
}

input[type="text"] .text
{
     border: 1px solid red; 
}

HTML code:

<div>
     <input type="text" class="text"/>
</div>

Guess what?​

Still Green.

Remove the space in 'input[type="text"] .text' it becomes input[type="text"].text . That's ok. The border color is red.

Upvotes: 2

Views: 14568

Answers (4)

Aurelio
Aurelio

Reputation: 25792

It's a matter of weight of your selectors.

With

input[type="text"]

You are passing both input and [type=text] as selector, so you're passing a total of two.

With

.text

You are passing only one. This translates in less weight and less specificity, so the first selector wins over the second.

By adding input before (i.e. input.text) you're adding more weight to second style, which will prevail as you'd expect from Cascading Style Sheets.

Specificity is easily visualized through websites like Specificity Calculator.

Upvotes: 0

TLS
TLS

Reputation: 3150

Styles are applied in sequence, but also must follow specificity rules. The .text is less specific than input[type="text"], so the green border "wins." If you make the red border rule more specific, you can get the results you seem to be expecting.

Try something like input.text and see what happens. If that doesn't do it, you'll have to get even more specific.

Upvotes: 0

leepowers
leepowers

Reputation: 38318

/* Set default border for `text` elements */
.text
{
     border: 1px solid red; 
}

/* Override for input elements */
input.text
{
     border: 1px solid green; 
}

Upvotes: 0

John Conde
John Conde

Reputation: 219834

The C in CSS stands for cascading. You just need to give it higher precedence then the other rule.

input.text
{
     border: 1px solid red ; 
}

Upvotes: 8

Related Questions