3

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

mCY
  • 2,731
  • 7
  • 25
  • 43

2 Answers2

7

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.

Rajshekar Reddy
  • 18,647
  • 3
  • 40
  • 59
1

Use important here.

.active {
    display: block !important;
}

Css id selector # has high priority so to make active work you need to use !important. However, i'll prefer to use the following way:

.tab {
  display: none;
}

.tab.active {
  display: block;
}
<div class="tab active" id="tab1"><p>This is CPU</p></div>
<div class="tab" id="tab2"><p>This is MEM</p></div>
<div class="tab" id="tab3"><p>This is Network IO Receive</p></div>
<div class="tab" id="tab4"><p>This is Network IO Send</p></div>
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95