How to affect only other links when one is being hovered

Viewed 51

I've been trying to make all other links shrink when one is being hovered, but so far it only shrinks the links afterwards the one being hovered

.navlink {
  width: 100px;
  display:inline-block;
  background-color: red;
}

.navlink:hover~.navlink {
  width: 50px;
}

.navlink:hover {
  width: 150px;
  background-color: pink;
}
<a class="navlink">link 1</a>
<a class="navlink">link 2</a>
<a class="navlink">link 3</a>
<a class="navlink">link 4</a>

3 Answers

You can try flexbox for this and you only need to adjust the hovered link and the other will shrink by default

.container {
  display: flex;
  width: 400px;
}

.navlink {
  flex: 1;
  margin: 0 5px;
  background-color: red;
  transition: 0.3s all;
}

.navlink:hover {
  flex: 3; /*Adjust this to control the size*/
  background-color: pink;
}
<div class="container">
  <a class="navlink">link 1</a>
  <a class="navlink">link 2</a>
  <a class="navlink">link 3</a>
  <a class="navlink">link 4</a>
</div>

I suggest making the width of the resize to be equal to that which it started. If you have four elements at 100px starting, which will make the total width 400px (plus any margin/padding stuff), then make the resized elements equal out to 400px as well to ensure that you are not getting any weird stuff.

.navlink {
  display: inline-block;
  width: 100px;
  background-color: red;
  transition: width 0.3s;
}

.container:hover .navlink:not(:hover) {
  width: 75px;
}

.navlink:hover {
  width: 175px;
  background-color: pink;
}
<div class="container">
  <a class="navlink">link 1</a>
  <a class="navlink">link 2</a>
  <a class="navlink">link 3</a>
  <a class="navlink">link 4</a>
</div>

try with this html code:

<div class="parent">
  <a class="navlink">link 1</a>
  <a class="navlink">link 2</a>
  <a class="navlink">link 3</a>
  <a class="navlink">link 4</a>
</div>

y css:

.navlink {
  width:100px;
  background-color:red;
  display:inline-block;
}
.parent:hover .navlink{
  width:50px;
}
.parent .navlink:hover{
  width:150px;
  background-color:pink;
}
Related