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>