-1

I am creating a website with a menu bar stored in another file (solution from here). I also have the css stored in a seperate file, linked to the menu bar:

<!--#include file="menu.html" -->

Each page on my website get's highlighted if it's the current page. However, Since my html is in a seperate file, I can't just add class="current" or something similar to that. This is what I came up with:

  • add css to each site selecting ul:nth-child(n) that adds all needed css.

If I change the order of the elements, everything will be messed up!
Is there a better way to add css later?

PAS
  • 115
  • 7

2 Answers2

1

You could add an id to the body of each page and another one to each menu item, and then apply the highlight styles when the menu id is contained in their associated body id.

For example if you have an about page you would use:

<body id="about-page">

</body>

The menu would have id's for each item:

<ul class="menu">
  <li id="main"><a hef="/">My page</a></li>
  <li id="shop"><a hef="/">Shop</a></li>
  <li id="about"><a hef="/">About me</a></li>
</ul>

And you would put the style rules in this way:

.menu {
  /* menu styles */
}

#main-page #main, #shop-page #shop, #about-page #about {
  /* styles for highlight the current page */
}
Alberto Martinez
  • 2,464
  • 4
  • 24
  • 27
0

I used an id scheme similar to my website's page layout, and applied a javascript function that split's the query into sections, and adds css to the desired id(s).

<link rel="stylesheet" href="menu.css" type="text/css"/>
<nav id="menu_wrap">
      <ul>
        <li><a id="home" href="/">Home</a></li>
        <li><a id="school" href="">School</a>
          <ul>
            <li><a id="trinomial" href="https://reteps.tk/school/trinomial_calculator">Trinomial Calculator</a></li>
            <li><a id="radical" href="https://reteps.tk/school/radical_calculator">Radical Calculator</a></li>
            <li><a id="grades" href="https://reteps.tk/school/grades_calculator">Grade Calculator</a></li>
            <li><a id="trig" href="https://reteps.tk/school/trig_calculator">Trig Calculator</a></li>
            <li><a id="kahoot" href="https://reteps.tk/school/kahoot_bot">Kahoot Bot</a></li>
          </ul>
        </li>
        <li><a href="/blog/home">Blog</a></li>
        <li><a href="/other">Other</a></li>
        <li><a href="https://github.com/reteps">Github</a></li>
      </ul>
</nav>
<script>
  var path = window.location.pathname;
  if (path == "/") {
    document.getElementById("home").style.background = "#27e8e8";
  } else {
    var sections = path.split("/");
    for (var i = 1;i < sections.length;i++) {
      document.getElementById(sections[i].split("_")[0]).style.background = "#27e8e8";
    }
  }
</script>
PAS
  • 115
  • 7