Creating a Hover Effect for DIV Elements Using Pure CSS, No JavaScript Needed

Imagine a straightforward, horizontal navigation on a website:

| Home | About | Products | Contact | Impress | ... or something like that...

A rectangular element is positioned above the navigation.

Now, I want this rectangle to automatically shift horizontally (left/right) based on which navigation item is being hovered over.

For instance:

  • If hovering over entry 2 ("About"), the rectangle should slide 5em to the right
  • If hovering over entry 5 ("Impress"), the rectangle should slide 20em to the right, and so on

HTML:

<div id="rectangle"></div>

<ul class="navigation">
    <li><a href="#">Entry 1</a></li>
    <li><a href="#">Entry 2</a></li>
    <li><a href="#">Entry 3</a></li>
    <li><a href="#">Entry 4</a></li>
    <li><a href="#">Entry 5</a></li>
</ul>

CSS:

I have not yet figured out how to achieve this using CSS. My initial approach would look similar to this:

#rectangle {
    background-color: powderblue;
    width: 10em;
    height: 2em;
    margin: 0 auto;
    position: absolute;
}

ul li:nth-child(1):hover ~ #rectangle {right:0em}
ul li:nth-child(2):hover ~ #rectangle {right:5em}
ul li:nth-child(3):hover ~ #rectangle {right:10em}
ul li:nth-child(4):hover ~ #rectangle {right:15em}
ul li:nth-child(5):hover ~ #rectangle {right:20em}

Unfortunately, this solution does not seem to work as expected. Have I made a mistake somewhere?

#rectangle {
  background-color: powderblue;
  width: 10em;
  height: 2em;
  margin: 0 auto;
  position: absolute;
}

ul li:nth-child(1):hover~#rectangle {
  right: 0em
}

ul li:nth-child(2):hover~#rectangle {
  right: 5em
}

ul li:nth-child(3):hover~#rectangle {
  right: 10em
}

ul li:nth-child(4):hover~#rectangle {
  right: 15em
}

ul li:nth-child(5):hover~#rectangle {
  right: 20em
}
<div id="rectangle"></div>

<ul class="navigation">
  <li><a href="#">Entry 1</a></li>
  <li><a href="#">Entry 2</a></li>
  <li><a href="#">Entry 3</a></li>
  <li><a href="#">Entry 4</a></li>
  <li><a href="#">Entry 5</a></li>
</ul>

Answer №1

To create a rectangle using a pseudo element, you can implement the following code without adding an extra element:

ul {
  position: relative;
  margin: 0;
  padding: 0;
}

ul li {
  display: inline-block;
}

ul li:last-child:after {
  content: '';
  background-color: powderblue;
  width: 10em;
  height: 2em;
  margin: 0 auto;
  position: absolute;
  z-index: -1;
  left: 0;
  transition: .4s ease-in-out;
}

ul li:nth-child(1):hover~li:last-child:after {
  transform: translateX(0em);
}

ul li:nth-child(2):hover~li:last-child:after {
  transform: translateX(5em);
}

ul li:nth-child(3):hover~li:last-child:after {
  transform: translateX(10em);
}

ul li:nth-child(4):hover~li:last-child:after {
  transform: translateX(15em);
}

ul li:nth-child(5):hover:after {
  transform: translateX(20em);
}
<ul class="navigation">
  <li><a href="#">Entry 1</a></li>
  <li><a href="#">Entry 2</a></li>
  <li><a href="#">Entry 3</a></li>
  <li><a href="#">Entry 4</a></li>
  <li><a href="#">Entry 5</a></li>
</ul>

Answer №2

To hide the regular div, you can apply the display:none; property and then utilize the :hover pseudo class to show the content when hovered over.

#mydiv {
display:none;
}
#mydiv:hover {
display:inline;
}

Answer №3

If you're looking to achieve this effect using only CSS, it's as simple as:

Add the class "navigation" to your HTML and style the li elements on hover

.navigation li:hover{
opacity: 0.9;
padding-left: 3px;
padding-right: 7px;
background-color:#f2f2f2;
transition: 0.9s;
}

Feel free to customize other aspects as needed...

Answer №4

It is not possible to achieve this using only CSS, but you can simulate the same effect by dynamically changing styles with jQuery when hovering over and out of elements.

$(function() {
  $('#a').hover(function() {
    $('#rectangle').css('right', '0em');
  }, function() {
   
    $('#rectangle').css('right', '');
  });
   $('#b').hover(function() {
    $('#rectangle').css('right', '5em');
  }, function() {
   
    $('#rectangle').css('right', '');
  });
   $('#c').hover(function() {
    $('#rectangle').css('right', '10em');
  }, function() {
    
    $('#rectangle').css('right', '');
  });
  $('#d').hover(function() {
    $('#rectangle').css('right', '15em');
  }, function() {
   
    $('#rectangle').css('right', '');
  });
  $('#e').hover(function() {
    $('#rectangle').css('right', '20em');
  }, function() {
   
    $('#rectangle').css('right', '');
  });
});
#rectangle {
    background-color: powderblue;
    width: 10em;
    height: 2em;
    margin: 0 auto;
    position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul class="navigation">
    <li><a href="#" id="a">Entry 1</a></li>
    <li><a href="#" id="b">Entry 2</a></li>
    <li><a href="#" id="c">Entry 3</a></li>
    <li><a href="#" id="d">Entry 4</a></li>
    <li><a href="#" id="e">Entry 5</a></li>
</ul>
<div id="rectangle"></div>

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

How to Efficiently Organize OpenAI AI Responses Using TypeScript/JavaScript and CSS

I'm using a Next.js framework to connect to the OpenAI API, and I've integrated it seamlessly with an AI npm package. The functionality is incredible, but I've encountered an issue regarding line breaks in the responses. You can find the AI ...

Angular Space-Friendly Table

After attempting to code the sample in Angular, I realized it wasn't what I was looking for. <table> <th >Number</th> <th >Merchant Name</th> ...

The quickForm Meteor encountered an exception in the template helper: There was an error stating that Recipes is not within the window

I'm having trouble getting the app to work on Meteor. The quickform is not connecting to my Collection. "Error: Recipes is not in the window scope" Can anyone offer assistance with this issue? Below is my quickform code: <template name="NewRe ...

Arrange the table by adding and editing before and after appending

I have a table data that needs to be dynamically appended. But I want to allow users to add new data using text input and also edit the existing data before and after it's appended. The problem is that when I append new data, it overwrites the previo ...

Angular 6: A guide to dynamically highlighting navbar elements based on scroll position

I am currently building a single page using Angular 6. The page is quite basic, and my goal is to emphasize the navbar based on scrolling. Below is the code snippet I am working with: .sticky { position: sticky; top: 0; } #i ul { list-style-type: ...

Utilizing a Clear Button to Reset Specific Fields in a Form Without Clearing the Entire Form

I am currently working on a multipart form that includes 'Name', 'Email', and 'Phone Number' fields. It's important to note that the phone number field is actually composed of 10 individual single-digit fields. To enhan ...

What is the best way to add an insert button to every row?

Take a look at the image provided. When I click on any register button, the last row is being inserted instead of the desired row. What I'm aiming for is this: when I click register, the entire selected row should be stored in a separate table. Whe ...

Using AJAX to submit a form and retrieve response data in Javascript

After successfully getting everything to post correctly, I encountered a problem with this script. It keeps loading the content into a new page. Could it be related to the way my php file returns it using "echo(json_encode($return_receipt));"? <s ...

Is it better to dynamically generate HTML elements or to just directly paste complete fragments in the code?

After manipulating the DOM and injecting AJAX content, I often find myself filling in the new content into a copied HTML fragment, then populating it with the updated information before using $().html() to insert the modified code back into the DOM. The ex ...

What is the predefined value for a multi-select generated by the ng-for directive in Angular?

I am having trouble setting default selected values for the multi-select. Despite trying various methods such as initializing the ngModel to bind the variable and using [selected] = "selectedSegment == 'S1'", none of them seem to be effective fo ...

Rearrange the position of one div to be placed next to another div and assign the float property

I have numerous divs located on my webpage, including .rightColumnBar and .divAttributes. HTML <div class="mainContent"> <div class="pageContent"> <form id="createLead" class="frmDiv clear" action="/leads/create_lead.html?lead_id=3287" nam ...

apostrophe cutting off a portion of the input field's value

I am facing an issue with a reloaded input box on a web page that is updated through an ajax call. Whenever the input contains a single quote, the rest of the value gets cut off. How can I resolve this problem? The value assigned to myVal dynamically from ...

Having trouble aligning and resizing text and divs accurately

Hello, I'm having trouble centering my text within a div and fitting three divs inside my content area. Here is the code snippet: HTML <div id="content"> <div class="latest"> <p>Gentlemen, these are my latest works< ...

Can you please specify the type of values being entered as input?

Query: How do I identify the data type of the value entered in an input field? Whenever I use typeof, it always returns string unless the string is empty. I searched various forums extensively but couldn't find a solution. Can someone assist me with t ...

Position a modal in the vertical center with scroll functionality for handling extensive content

Looking for ways to tweak a Modal's CSS and HTML? Check out the code snippets below: div.backdrop { background-color: rgba(0, 0, 0, 0.4); height: 100%; left: 0; overflow: auto; position: fixed; top: 0; width: 100%; z-index: 2020; } ...

The Yeoman/Grunt-usemin is failing to update the index.html file even after adding new JavaScript code

As I work on developing a web app using Yeoman and the Angular generator on Windows 7, I go through the process of running 'yo angular' followed by 'grunt' to build the app for deployment. The index.html file in the dist folder gets upd ...

Disappearance of icon upon hovering in CSS

I am currently working with Angular JS (1.x) and I have a requirement to display tooltip text when hovering over an info icon. The tooltip text appears properly, but the issue is that the icon disappears when hovered over. It reappears once the hover is re ...

Adjustable div heights for text within inline elements

How can I make two inline-table divs (content and sidebar) have the same height regardless of their content? I've experimented with various attributes, but nothing seems to be working. You can view my website here. ...

What is the best way to align an element next to another using id or class?

I am looking to align the search element next to either "Media Heading 1" or "Media Heading 2" based on their id/class. For instance: Assume I have an element with the class of "media-item-1" and I aim to position the search div alongside that element us ...

Having trouble correctly parsing XML data using JavaScript

My input field contains the following XML code: <?xml version="1.0" encoding="utf-8"?> <players timestamp="1536505850"> <player id="0518" name="Eagles, Philadelphia" position="Def" team="PHI" /> <player id="10271" name="Jones, Jul ...