Tudor Apostol
Tudor Apostol

Reputation: 131

Overwrite parent style

I've got the following html and css

.a {
  text-align: center;
  a {
    text-decoration: none;
    color: $blue;
    font-size: 1.2rem;
    font-weight: 700;
  }
}

.btn {
  display: block;
  padding: 1rem 2.5rem;
  text-align: center;
  text-decoration: none;
  font-size: $medium;
  font-weight: $bold;
  cursor: pointer;
  &-grey {
    background-color: $light-grey;
    color: $grey;
  }
  &:hover {
    background-color: $green;
    color: white;
  }
}
<div class="a">
  <a class="btn btn-grey" href="#">Link</a>
  <a href="#">Another Link</a>
</div>

I have styles for the a div that needs to affect the classless anchor tag, and at the same time I need the a tag with the btn class to have a different style. Needless to say, they both inherit the style I declared on the parent.

Is there an optimal and fully supported way to either overlook inheritence or increase specificity ?

I'm using Sass and the btn is styled in a different file, if I would nest it inside the parent it works as expected.

Upvotes: 0

Views: 50

Answers (1)

JoelBonetR
JoelBonetR

Reputation: 1572

There's a pseudo selector

:not(.class)

.a {
    text-align: center;

    a {
        text-decoration: none;
        color: $blue;
        font-size: 1.2rem;
        font-weight: 700;
    }
}


.btn {
    display: block;
    padding: 1rem 2.5rem;
    text-align: center;
    text-decoration: none;
    font-size: $medium;
    font-weight: $bold;
    cursor: pointer;

    &-grey {
        background-color: $light-grey;
        color: $grey;
    }

    &:hover {
        background-color: $green;
        color: white;
    }
}
div.a > a:not(.btn){
    text-decoration: none;
    color: red;
}
div.a > a:not(.btn):hover{
    color: green;
}
<div class="a">
    <a class="btn" href="#">Link</a>
    <a href="#">Another Link</a>
</div>

EDIT

Added pseudo selector to show how you can set two in a row to increase specificity of the selector.

Upvotes: 2

Related Questions