0

Can someone tell me if there is a spicificity among CSS properies?

I am testing flexbox and I tried this scenario:

The second selector .flex-basis-5 is applied via JS on some kind of condition. I was expecting the value of flex-basis to be overwritten by new selector, but it's only applied if I add !important to it.

.flex-container {
  display: flex;
  flex-flow: row wrap;
}

.flex-item-7 {
  flex: 0 0 58.33%
}

.flex-basis-5 {
  flex-basis: 41.66%;
}
<div class="flex-container">    
   <div class="flex-item-7 flex-basis-5">Some content</div>
</div>

Thanks!

Marc DG
  • 51
  • 10

1 Answers1

0

Specificity is based on the selector, not the property. Properties applied to a selector are applied in the order written, so lower down properties within the set will override higher up values.

This said, your code works if I understand you correctly. Here's a demo:

const btn = document.getElementById("toggle")
btn.addEventListener("click", () => {
  document.querySelector(".flex-item-7").classList.toggle("flex-basis-5")
})
.flex-container {
  display: flex;
  flex-flow: row wrap;
}

.flex-item-7 {
  flex: 0 0 58.33%;
  background: #ccc;
}

.flex-basis-5 {
  flex-basis: 41.66%;
}

button {
  margin-top: 2em;
}
<div class="flex-container">    
   <div class="flex-item-7 flex-basis-5">Some content</div>
</div>

<button id="toggle">Toggle .flex-basis-5</button>

If you're seeing something different in your app, it's likely that you have .flex-basis-5 defined above .flex-item-7, so it has lower precedence and is being overridden by the later-defined styles.

coreyward
  • 77,547
  • 20
  • 137
  • 166
  • That was fast!! Thank you coreyward for your speedy answer it makes sense. I was only looking at the order the selectors where applied to the element. – Marc DG Dec 09 '20 at 02:08
  • Precedence is the right word in this case! – Marc DG Dec 09 '20 at 02:10