Joey Yi Zhao
Joey Yi Zhao

Reputation: 42604

How to override css styles when @extend from other class in scss?

I have scss code:

.a {
    height: 100px;
    width: 100px;
}

.b {
    @extend .a;
    height: 200px;
}

The compiled css looks like:

.a, .b {
    height: 100px;
    width: 100px;
}

.b {
    height: 200px;
}

when I apply this style the dom <div class="a b"> will have the height of 100px instead of 200px. How can I make the css take the height 200px in this case?

Upvotes: 8

Views: 6306

Answers (4)

Yevgeniy Afanasyev
Yevgeniy Afanasyev

Reputation: 41430

you can use a wrapper

.a {
    height: 100px;
    width: 100px;
}

.b {
    @extend .a;
}

.wrapper .b {
    height: 200px;
}

HTML

<div class='wrapper'><div class='b'> XXX </div></div>

You can also use !important.

.a {
    height: 100px;
    width: 100px;
}

.b {
    @extend .a;
    height: 200px !important;
}

Upvotes: 0

Hanif
Hanif

Reputation: 3795

Then which selector in most below this will apply this is general rule for any CSS file.

Height will be <div class="a b"> 200px;

.a {
    height: 100px;
    width: 100px;
    }   
.b {
    @extend .a;
    height: 200px;
}

Height will be <div class="a b"> 100px;

.b {
    @extend .a;
    height: 200px;
}
.a {
    height: 100px;
    width: 100px;
}

Always height will be <div class="a b"> 200px order dose not matter;

.a {
    height: 100px;
    width: 100px;
    &.b {
       height: 200px;
    }
}

Upvotes: 4

jdickel
jdickel

Reputation: 1457

This already does exactly what you want.

You might have the .b above your .a, .b then the latest style wins.

Read up on cascading order

Finally, sort by order specified: if two declarations have the same weight, origin and specificity, the latter specified wins. Declarations in imported style sheets are considered to be before any declarations in the style sheet itself.

.a, .b {
    height: 100px;
    width: 100px;
}

.b {
    height: 200px;
}

/* ignore */
div{
  background-color: red;
}
body{
  display: inline-flex;
}
<div class="a"></div>
<span>|</span>
<div class="b"></div>
<span>|</span>
<div class="a b"></div>

Upvotes: 4

Abin Thaha
Abin Thaha

Reputation: 4643

If my understanding of your question is right, It cannot be overridden like

.a, .b {
    height: 100px;
    width: 200px;
}

Because, it will apply width: 200px; to both .a and .b, what you need is to apply width: 200px; to .b only, right? In that way, the code you provided works perfect already.

Upvotes: 0

Related Questions