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

Using preventDefault in the compositionend event does not make any difference

var inputNode = document.getElementById('view_1'); inputNode.addEventListener('compositionend', function(e) { console.log(e.cancelable); // true e.preventDefault(); }); <div id="view_1" class="view" contenteditable="true> &l ...

Remove the color gradient for the column headers in the Google Visualization table

Whenever I attempt to change the colors of the column headers using the method demonstrated in this insightful source, a rather generic gradient is applied. Interestingly, the example code provided also demonstrates the same default gradient on the secon ...

Guide to making a single row beneath two columns using CSS Grid

My goal is to utilize CSS Grid in order to design a blurb layout featuring 2 columns at the top and a full row below. This will allow for an FA Icon and Title, accompanied by a full description below, similar to the image provided. I believe I have succes ...

Creating a responsive canvas and image container in fabric.js involves adjusting the layout and size of the

I am working with fabric.js and canvas to dynamically add an image from a URL. I would like to make the canvas responsive based on the resolution. How can this be achieved? Here is my current code: <canvas id="panel" width="700" height="350"></ ...

Ways to troubleshoot React JSX/HTML input issue displaying as -$NaN.undefined

https://i.sstatic.net/1xIvb.pnghttps://i.sstatic.net/aeQrS.pngI'm currently facing an issue while trying to implement an input field that subtracts a number from another computed value within an HTML table setup. I've noticed that everything work ...

I am currently working with CakePHP and am interested in learning how to expire the admin session

I'm having issues with the code in my UserController. When I open the admin panel in two tabs within the same browser and log out from one tab, I am unable to redirect to the login page from the other tab when clicking on any menu. function beforeFil ...

Setting the image source for each image in a table using VB.net

Is it more efficient to loop through the img src of various cells using a For Each loop and set their src based on another value (x) by directly referencing the img src attributes in code, or would embedding the table in a control higher up the hierarchy ...

When implementing auto-generated IDs in HTML forms, rely on randomly generated values for increased uniqueness

When developing a form with multiple complex controls built as Backbone views, one wants to ensure that the labels are correctly linked to the input elements. This is typically done using the "for" attribute. However, in cases where the same control needs ...

Clicking on the Edit button does not result in any changes to the HTML on the page following a table

My current setup involves a button that is supposed to toggle between 'Add New User' and 'Update User' elements when clicked. However, it seems to work only when the table has not been filtered. Once I apply any kind of filtering on the ...

"I am looking for a way to retrieve dynamic data from a (click) event in Angular. Can

Within my component, I have a video loaded in an i tag on a click event. The challenge is accessing the video ID from the video.component.ts file in order to dynamically load a new video. The solution has been elusive so far. <li *ngFor="let video of c ...

What is the best way to retrieve the content of a specific class in Selenium WebDriver?

Python Code : from selenium import webdriver from selenium.webdriver.chrome.options import Options options = webdriver.ChromeOptions() options.add_argument(r"--user-data-dir=C:\Users\bji\AppData\Local\Google\Chrome\ ...

Utilizing Boostrap to create a background image positioned on the far left of the screen within a .container

I am currently working with bootstrap 4 and have a layout that includes a container class: body #content.container .row .col-6 | Great content .col-6 | I really like it .row .col-12 And so forth .row ...

JavaScript must be able to detect when the checkbox value is reversed, which is dependent on the user-entered data

Hey there, I come across a situation where users are selecting a checkbox to insert or update a row of data in a MySQL database through SparkJava/ Java. The functionality is working fine except for a minor glitch. The issue arises when the checkbox behav ...

What is the best method for connecting my HTML to jQuery code?

Apologies for my lack of experience in coding, but I will try to keep this brief. To put it simply, when I insert my jQuery code directly into the HTML file below the content, it works perfectly - the element I want to animate 'hides' and then & ...

Using Tailwind CSS's width property w-11/12 actually returns a full 100% width instead of the expected 91.66

It seems that the w-11/12 class is not behaving as expected. According to the documentation, it should give a width of 91.666% but instead, it's filling up 100%. This issue only occurs with the value 11, while other values work fine. Has anyone else e ...

Incomplete Rotation CSS Animation

I am attempting to create a horizontal spinning image using only CSS3. Check out my webpage here: You can find the CSS file here: www.csupomona.edu/~lannguyen/ISSM_WEB/css/main.css The code for calling the spin effect is at the top, with the actual imp ...

What is the best way to design lists that adjust to different screen sizes by incorporating multiple columns within the available width?

Back in my old fixed-width days, I had a clever method of distributing data across three columns by dividing the number of elements by three. It worked pretty efficiently. Now in this modern responsive world, my current solution involves splitting data in ...

AngularJS enables the loading of directives dynamically, but sometimes encounters errors such as "Restricted URI access denied."

Presently, I am in the process of developing a small educational project using HTML5, CSS, JS and AngularJS. Hiccup: Loading an AngularJS Directive in my index.html file Error code [1] - Local browser Error: Access to restricted URI denied Various resp ...

Increase the size of a div to equal the combined width of two divs located directly below it

I need help aligning 3 divs so that the top div stretches to match the width of the bottom 2 divs combined. Here is an image showing the expected div positioning. I attempted to use display: table-row for the divs. <div id="main_div" style="display: ta ...

Picture is not appearing on web browser within Node application

Recently, while working with Visual Studio Code, I decided to incorporate an image into my Node project. After downloading the image from the internet and placing it in the directory, I renamed it to 'file_2.jpeg'. I then included <img src = " ...