Assumed we have a simple, horizontal navigation of a website:
| Home | About | Products | Contact | Impress | ... or similar...
Above the navigation there is a rectangle placed.
Now I want to automatically "slide" this rectangle horizontally (left/right), depending on the navigation entry that is currently hovered.
Example:
- If entry 2 ("About") is hovered, the rectangle should slide 5em to the right
- If entry 5 ("Impress") is hovered, the rectangle should slide 20em to the right, etc.
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 am not yet sure on how to solve this in CSS. My approach would be something like that:
#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 does not work as expected. Did I do something wrong?
#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>
ul li:nth-child(1):hover ~ #rectangleassumes that the element with the id "rectangle" is a sibling of thelielement, following it. This is not the case with your markup. See developer.mozilla.org/en-US/docs/Web/CSS/CSS_Selectorsliare otherlis. Maybe make the rectangle anli? Note thatrightadjusts the element's position from the right, so an element with a higherrightvalue is actually farther to the left than one with a smallerrightvalue.