user1476512 user1476512 - 6 months ago 15
CSS Question

override css div display: none;

Thanks for your time! The codes are very simple. I suppose it should display "This is CPU". But it didn't. Where am I wrong?

Fiddle

For people who cannot open Fiddle, here's the codes:

HTML:

<div id="tab1" class="active" ><p>This is CPU</p></div>
<div id="tab2"><p>This is MEM</p></div>
<div id="tab3"><p>This is Network IO Receive</p></div>
<div id="tab4"><p>This is Network IO Send</p></div>


CSS:

#tab1, #tab2, #tab3, #tab4 {
display: none;
}

.active {
display: block;
}


By add
!important
it do works. But why if I changes all the ids to classes, it could work?

e.g.: Fiddle

Answer

The major thing to note here is the CSS priorities

In this scenario the Rule provided using Id will have more priority over the class

You need to use combination of your id and class to create a even more priority than just the id

#tab1, #tab2, #tab3, #tab4 {
  display: none;
}

#tab1.active , #tab2.active , #tab3.active , #tab4.active {
  display: block;
}

You can also use partial selectors to reduce the code..

[id^=tab].active{
 display: block;
}

Note : Do not use !important unless you have no other option left. In most of the cases the work can be done without using!importantat all.