1

Currently I´m highlighting the active tab in my site with just a CSS class, the problem is that I´m having more and more tabs and this list is getting bigger and every time I add a new tab I also need to add a new selector to the class

Is there a CSS only way to simplify this?

body.students li.students,
body.teachers li.teachers,
body.sports li.sports,
...,
... {
    background-color: #000;
}

I´m adding the class to the body for each section is there a way to do something like this with CSS?

body.[class] > li.[class] {
    background-color: #000;
}

Basically I just want to add a property if both (body and li) have the same class

Example for students.html

<body class="students">
    <ul>
        <li class="students">students</li>
        <li class="teachers">teachers</li>
</body>

In this example li.students is the one that will be highlighted

Example for teachers.html

<body class="teachers">
    <ul>
        <li class="students">students</li>
        <li class="teachers">teachers</li>
</body>

In this example li.teachers is the one that will be highlighted

Thanks!

Awais
  • 4,752
  • 4
  • 17
  • 40
handsome
  • 2,335
  • 7
  • 45
  • 73

1 Answers1

0

Change your HTML code - introduce a class "current_page" (or whatever you'd like to call it)

<body class="students">
    <ul>
        <li class="students current_page">students</li>
        <li class="teachers">teachers</li>
    </ul>
</body>

Or

<body class="teachers ">
    <ul>
        <li class="students">students</li>
        <li class="teachers current_page">teachers</li>
    </ul>
</body>

That way, you'll only ever need one selector:

li.current_page {
    background-color: #000;
}

You could also do it in JavaScript if you don't like to change your HTML code:

var classname = document.querySelector("body").className;
var li = document.querySelector("li." + classname);
li.className = li.className + " current_page";
Imanuel
  • 3,596
  • 4
  • 24
  • 46