Is it possible to execute this navigation using only CSS?

Feeling a little stuck here. I've managed to create most of what you see in the image below. However, I'm having trouble with setting up a feature where clicking one of the links turns the line below red after the next page loads. I know I'll need to use jQuery to detect the page and add inline CSS, but I want to make this process as simple as possible for others who might use this template. I considered using a li element for this purpose, but haven't quite figured it out yet. Any ideas on how to achieve this seamlessly?

Answer №1

A method suggested by jackJoe involves setting the active class server-side on the current page, but another option is using pure CSS with some advance planning.

To implement this, start by assigning an id attribute to the body tag of your page, which is a good habit to develop. Then, your CSS file will utilize that body id to determine which list item should be marked as "active".

Here is a snippet of the page code:

<body id="main"> <!-- update this id for each page -->
    <ul>
        <li class="main-nav"><a href="#">Main</a></li>
        <li class="community-nav"><a href="/community">Community</a></li>
        <li class="search-nav"><a href="/search">Search</a></li>
    </ul>
</body>

Example CSS styling:

li.main-nav,
li.community-nav,
li.search-nav
{
    background: #FFF;
    /* other styles */
}

#main li.main-nav,
#community li.community-nav,
#search li.search-nav
{
    /* style the active tab differently */
    background: #F00;
}

This approach allows the navigation section's HTML code to remain consistent across all pages without the need for server-side rendering or client-side modifications.

You can find more information about this technique on CSS Tricks: ID Your Body For Greater CSS Control and Specificity

Answer №2

It's pretty simple. Just create a class to represent the "active" state and apply styles to it:

<li class="active">Home</li>

You can customize the styles depending on the structure of your HTML elements.

CSS:

.active {
    border-bottom: 3px red solid;
}

All you have to do is add the class when the page loads (for example, server-side)

Answer №3

To structure your menu in HTML, follow this format:

<body id='Search' >
    <div id='menu'>
        <div class='bars'></div>
        <a href='/home/' title='Home'>Home</a>
        <a href='/community/' title='Community'>Community</a>
        <a href='/search/' title='Search'>Search</a>
        <a href='/contact/' title='Contact'>Contact</a>
        <div class='bars shift'></div>            
    </div>
</body>

Remember to assign a unique id to the body tag as suggested by Cody. This id should match the value of the title attribute for each menu link.

Next, apply the following CSS styles:

.bars {border-top:1px solid #CCC;border-bottom:1px solid #CCC;height:5px;}
.shift {margin-top:-6px;}
#menu {font-family:arial;font-size:12pt;text-align:center;}    
#menu a {display:inline-block;padding:7px;text-decoration:none;color:#000;}
.active {border-bottom:5px solid red;}

Include this jQuery script on each page:

$(document).ready(function(){
    var id = $('body').attr('id');
    $('#menu a').each(function () {
        var title = $(this).attr('title');
        $(this).removeClass('active');
        if (title == id) $(this).addClass('active');
    });
});

For a live demonstration, visit this link and change the body element's id to see how it works.

Additionally, this method eliminates the need to constantly adjust CSS when modifying the HTML menu, unlike other approaches. While it relies on jQuery, you can opt for a pure CSS solution by directly applying the .active class based on the current page. This technique can also be adapted for use with <li> elements if needed.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The footer displays a flickering effect while navigating between pages

Here is the code snippet I'm using to display a fixed footer in the main layout: <nav class="main-footer navbar navbar-expand navbar-white navbar-light" style="height: 40px;"> <ul class="navbar-nav"> ...

Adjust text alignment based on the mobile device screen size using Bootstrap 4

On smaller devices, the layout of my horizontal label and text field is not as I expected. It appears like the image below: https://i.sstatic.net/9I8Os.png I am trying to make the First Name label left-aligned on small devices. Here is the code I have be ...

Align pictures in the middle of two divisions within a segment

This is the current code: HTML: <section class="sponsorSection"> <div class="sponsorImageRow"> <div class="sponsorImageColumn"> <img src="img/kvadrat_logo.png" class="sponsorpicture1"/> </div& ...

Processing of an array received via AJAX and passed to a PHP script, inside a separate function in a different file

I have a JavaScript array that I am sending via AJAX to a PHP file named aux.php. What I want is for this array to be visible and manipulable within a function inside a class in another PHP file called payments.php. I've provided all the code so they ...

Attempting to access getElementsByTagName() on a non-existent object

I've been searching extensively on how to resolve this issue without much success. I have multiple XML files with varying fields, and I'm running functions to check for these fields and display the information. My goal is to print the info if the ...

Selenium reports a selected element as Null

I am seeking to implement a dynamic waiting time for crawling data. Below is the HTML structure: <tr class="mv-quote-row" style="border-top-width: 1px;"> <td style="text-align: left;">Week 34/21</td> <t ...

What is the process for bringing an array from a .js file into an HTML document?

Exploring the world of JS and HTML, I recently came across an assignment that involved working with a file named stocks.js, which houses an array of stock information: 'use strict'; const stocks = [ { company: 'Splunk', symbol: &ap ...

Switch between dynamically generated div elements

Currently, I am in the process of developing my own lightweight blogging platform as a way to enhance my skills in PHP and jQuery without depending on Wordpress. The pagination system I have created displays 5 blog posts per page using PHP. However, within ...

creating an interactive element that seamlessly integrates with a dynamic background image slideshow

Struggling to make this work correctly as a newbie in javascript. I need the background image to slide upon hover and stay active on its selected div when clicked. The html, css, and javascript I have currently work fine - when the user clicks on a div, a ...

How to center text both horizontally and vertically in HTML

I am struggling with centering a background image along with a 1-line text vertically and horizontally inside a div. Although I have successfully centered the image, the text remains misaligned. I attempted using vertical-align: middle without success. Be ...

Neither of the squares are appearing on the canvas

Here is the code snippet I'm working with: const target = document.getElementById("target"); const context = target.getContext("2d"); function drawSquare() { context.fillStyle = "rgb(200, 0, 0)"; co ...

Minimizing the use of line breaks in HTML to enhance visual design characteristics

While working with Bootstrap and HTML to construct a website, I have frequently resorted to using line breaks in the code for design purposes. However, I believe there must be a more professional approach to achieve the desired layout. For instance, on ...

What is the process for altering the background color in this html5up template?

I am struggling to change the brown background color on my website. Despite updating various color values in the CSS file such as'backgroundcolor', I seem unable to make any changes. I have tried altering multiple color entries, but nothing seems ...

What could be causing my page to suddenly disappear?

After saving my changes in the IDE and refreshing the browser to test the prompt() function in my index.js file, the entire page goes blank, showing only a white screen. I double-checked the syntax of my function and it seems correct. Everything else on th ...

React forms are experiencing issues with characters overlapping

Having trouble with overlapping label and input letters in my React form. Looking for: The appearance shown in the top image Experiencing: What is displayed in the bottom image Any solutions on how to resolve this issue? https://i.sstatic.net/Y3W2m.png ...

Learn the process of utilizing Javascript to substitute additional texts with (...) in your content

I am facing a challenge with a text field that allows users to input text. I want to use JavaScript to retrieve the text from the textbox and display it in a paragraph. However, my issue is that I have set a character limit of 50. If a user exceeds this li ...

CSS hide/show

I implemented a CSS Expand/Collapse div from an existing code snippet available here. The default behavior hides the text, but I would like it to expand after clicking on it. Does anyone have any suggestions on how I can tweak this code so that the text i ...

Unable to wrap the strings from the database in a span element

I have a challenge where I need to enclose the first and last strings that represent the title and price of a product within a div using a span tag. These strings are dynamic, sourced from a database, and differ for each product. I have attempted to use th ...

Capturing and storing user input from a website onto a mobile device

Currently, I am in the process of building a website using HTML, CSS, and Javascript. This site will enable users to create their own digital flashcards. However, my goal is to implement a feature that saves these flashcards to the internal storage of the ...

Utilize one ajax response for three distinct sections/divisions

After making an ajax call, I am receiving a total of 27 results that I need to divide equally into three sections, with 9 results in each. The sections are displayed below: HTML: <div id="content"> <section> </section> <s ...