n179911
n179911

Reputation: 20341

How to create a CSS style which override another CSS style

I have 2 CSS styles which pretty much the same except one specific 'width' and the other does not. How can I create a CSS style which inherits another CSS style but override a property?

  .FirstStyle
    {
        margin: 0px 0px 0px 8px;
        position: relative;
        display: inline-block;

        height: 29px;
        width: 5px;

        float: left;
    }


    .SecondStyle
    {
        margin: 0px 0px 0px 8px;
        position: relative;
        display: inline-block;

        height: 29px;

        float: left;
    }

Upvotes: 0

Views: 2871

Answers (3)

agustin
agustin

Reputation: 2407

You can calculate the CSS specificity value

enter image description here

  1. If the element has inline styling, that automatically wins (1,0,0,0 points)
  2. For each ID value, apply 0,1,0,0 points
  3. For each class value (or pseudo-class or attribute selector), apply 0,0,1,0 points
  4. For each element reference, apply 0,0,0,1 point

Notes

  1. The universal selector (*) has no specificity value (0,0,0,0)
  2. Pseudo-elements (e.g. :first-line) get 0,0,0,1 unlike their pseudo-class brethren which get 0,0,1,0
  3. The pseudo-class :not() adds no specificity by itself, only what's inside it's parentheses.
  4. The !important value appended a CSS property value is an automatic win. It overrides even inline styles from the markup. The only way an !important value can be overridden is with another !important rule declared later in the CSS and with equal or great specificity value otherwise. You could think of it as adding 1,0,0,0,0 to the specificity value

Upvotes: 0

AndrewL64
AndrewL64

Reputation: 16341

How can I create a CSS style which inherits another CSS style but override a property?

The succeeding css styling automatically overrides the preceding property so just add the property below the one you want to override and it'll inherit everything except the new styling specified.

Example:

HTML:

<div class="someClass anotherClass">
   ....
</div>

CSS:

.someClass {
    width: 100px;
    color: green;
}
.anotherClass {
    width: 200px; <-- This will override the above values
    color: red;
}
.someClass {
    width: 450px !important; <-- The !important tag will override both suceeding as well as preceeding properties
}
.someClass {
    width: 500px; <-- This will override the first two styling properties
}

Upvotes: 1

ScaisEdge
ScaisEdge

Reputation: 133400

You can do try this way

In the two class above the width is not defined

.FirstStyle, .SecondStyle
{
    margin: 0px 0px 0px 8px;
    position: relative;
    display: inline-block;

    height: 29px;
    width: 5px;

    float: left;
}

Here you define the width only for the FirstStyle Class .. (and anyway do the fact this class is below the others could override an eventually width specified above )

.FirtsStyle
{
    width: 5px;
}

Upvotes: 1

Related Questions