Mustafa
Mustafa

Reputation: 1776

Why is this CSS class styling order-dependent?

.container {
   border: 4px solid;
}

and another class

.border-red {
   border-color:red;
}

and my html

<div class="container border-red"> </div>

The border color does not apply to the element unless i put the .border-red class before .container

Please check for demo JSFIddle

Upvotes: 2

Views: 168

Answers (4)

Salman Arshad
Salman Arshad

Reputation: 272106

The border property is a shortcut that sets (and overwrite) three properties at once:

  • border-width (Default value medium)
  • border-style (Default value none)
  • border-color (Default value is the value of the element's color property)

Declaring border after border-color overwrites the three properties even if you do not explicitly specify all three values.

The solution is to break your rule and list only the properties that you want to change. This works regardless of the order of rules:

.border-red {
    border-color:red;
}
.container {
    border-style: solid;
    border-width: 4px ;
}

Upvotes: 1

Fabrizio Calderan
Fabrizio Calderan

Reputation: 123387

this happens because the .container class overrides the colour of the border defined in the .border-red class

Without using !important I would change like so

.container {
   border-width: 4px;
   border-style: solid;
}

.border-red {
   border-color:red;
}

Upvotes: 1

Mihai Stancu
Mihai Stancu

Reputation: 16107

It is order dependent because border: is a shorthand of border-style: + border-width: + border-color:.

Upvotes: 2

Paulie_D
Paulie_D

Reputation: 115046

The reason is that this

.container {
   border: 4px solid;
}

is actually shorthand for

.container {
   border-width: 4px;
   border-style: solid;
   border-color: ** current font color **;
}

Consequently, the later style overrides the previous border-color declaration.

Border @ MDN

Upvotes: 5

Related Questions