1

I am trying to get this line effect to work when a user hovers over a link but for some reason the first two links are skipped. Why are the first two links not triggering the hover pseudo?

hr {
    width: 0%;
    margin: 0;
    padding: 0;
    border-top: 3px solid #6F42C1;
    transition: width 0.9s ease, margin-left 0.9s ease;
}

#test1-button:hover + #menu-line {
    width: 80%;
    margin-left: 0%;
}

#test2-button:hover + #menu-line {
    width: 80%;
    margin-left: 7%;
}

#test3-button:hover + #menu-line {
    width: 80%;
    margin-left: 15%;
}
<!DOCTYPE html>
<html>
<head>

</head>
<body>

<a href"#" id="test1-button">Test 1</a>&nbsp;&nbsp;&nbsp;&nbsp;
<a href"#" id="test2-button">Test 2</a>&nbsp;&nbsp;&nbsp;&nbsp;
<a href"#" id="test3-button">Test 3</a>
<hr id="menu-line">

</body>
</html>
Johannes
  • 64,305
  • 18
  • 73
  • 130
Robert Keith
  • 104
  • 2
  • 8

2 Answers2

2

Because on hover you are triggering the next element, that is the reason why only last one works.

Use ~ instead of +

sasa
  • 399
  • 2
  • 8
1

The + is the adjacent sibling combinator, which will only target the element directly adjacent. Below I've swapped in the general sibling combinator (~), which will work for your use case:

hr {
    width: 0%;
    margin: 0;
    padding: 0;
    border-top: 3px solid #6F42C1;
    transition: width 0.9s ease, margin-left 0.9s ease;
}

#test1-button:hover ~ #menu-line {
    width: 80%;
    margin-left: 0%;
}

#test2-button:hover ~ #menu-line {
    width: 80%;
    margin-left: 7%;
}

#test3-button:hover ~ #menu-line {
    width: 80%;
    margin-left: 15%;
}
<!DOCTYPE html>
<html>
<head>

</head>
<body>

<a href"#" id="test1-button">Test 1</a>&nbsp;&nbsp;&nbsp;&nbsp;
<a href"#" id="test2-button">Test 2</a>&nbsp;&nbsp;&nbsp;&nbsp;
<a href"#" id="test3-button">Test 3</a>
<hr id="menu-line">

</body>
</html>
Alexander Nied
  • 12,804
  • 4
  • 25
  • 45