menu
up-caret
down-caret

CodePen

Hey Everybody! Come share Pens, ask front-end coding questions, and get/give feedback with your CodePen pals

Trending conversations
Escape Room!
@rosieebob · 3d
Editing the code of a pen?
@connor-sneddon · 1d
Multiple Image with box shadow !
@mominriyadh · 3d
Hey guys
@foxirisad · 4d
Designing quotes
@nkhalqi · 2d

sibling hover wont work

February 12, 2019 at 3:06am

.qna h2:hover ~ .qna h1{

background:red;

padding:20px;

}

I just want the h1 to change if I hover over h2. Am I using the right coding?


February 12, 2019 at 3:38am

Can you include your HTML as well? Do you have a pen you’re working on?

I believe I see what's happening. You don't need to list .qna twice. It should look like this since the h1 is the sibling of h2, not .qna: .qna h2:hover ~ h1

If both the h2 and the h1 have .qna wrappers, you'll need to exclude the h2 and do it more like this: .qna:hover ~ .qna h1

Edited
  • reply
  • like

That only works if the element being hovered is on the DOM before the element to change, so when you try to do a h2 hover to affect an h1 that comes before, it won't work

  • reply
  • like

You could put the h2 first and then the h1, use display the div as flex and set the flex-direction as reverse (column reverse or row-reverse) and that will work

like-fill
1
  • reply
  • like

February 12, 2019 at 4:13pm

^yes! I'm not sure exactly what problem you're attempting to solve, @luvbatlotsnlots, but @erickmack's solutions is a great fix, and one I've used several times before.

Try this CSS if you want the elements next to each other AND if the h2 and h1 are siblings; what I stated in my prior comment is still necessary: .qna { display: flex; flex-direction: row-reverse; }

Add this style if you want them stacked: .qna { display: flex; flex-direction: column-reverse; }

Notice that I'm applying these styles to the .qna elements themselves, not their children h1 & h2. You will also need to have the elements' actual order reversed, as Erick had mentioned, so the html will be: <div class="qna"><h2></h2><h1></h1></div>

You may also want to play around with the align-items and justify-content CSS properties on the .qna element to adjust the way your elements are spaced and aligned.

  • reply
  • like