0

I want to animate two images within my #header div. Currently, when you hover over the individual images, they move to their respective positions. But I want to move my first image down and my second image up at the same time - when hovering over the #header div.

.set {
    position: relative;
    top: -15px;
    transition: top ease 0.5s;
}

.set:hover{
    top: 15px;
}

.rise {
    position: relative;
    top: 0;
    transition: top ease 0.5s;
}

.rise:hover {
  top: -15px;
}
    <div id="header">
        <header>
            <h1>My Title!</h1>
            <img src="https://i.pinimg.com/originals/71/ba/35/71ba3562bc89f6a11e5d5625da09bfeb.png" alt="sun" width="100px" class="set">
            <img src="https://i.ibb.co/z6PQ7qX/moon.png" alt="moon" width="100px" class="rise">
        </header>
    </div>
nobhad
  • 3
  • 2

1 Answers1

0

I would suggest to group both images together in element, and offset the images when that wrapper-element is hovered over. And when hovering over an individual image, override that offset.

That way, everything that is not hovered over, is being offset the opposite way.

Sidenote:
I removed the classes as well as the <div id="header">-tag. Reason is, the images can be selected quite easily even without a class, and secondly, because there is already an element purposed as a header semantically.

The display: flex; flex-flow: column; on <header> and the align-self: flex-start on <div> are to keep the layout-flow vertically and the <div> at minimum size.
Without the align-self: flex-start, the <div> would stretch out, filling the rest of the row (basically width: 100%), which would result in unwanted behavior when hovering over it.

header {
  display: flex;
  flex-flow:column;
}
header > div {align-self: flex-start}
header > div > img {
  width: 100px;
  transition: transform 0.5s;
}
header > div:hover > img {transform: translateY(-15px)}
header > div:hover > img:hover {transform: translateY(15px)}
<header>
  <h1>My Title!</h1>
  <div>
    <img src="https://i.pinimg.com/originals/71/ba/35/71ba3562bc89f6a11e5d5625da09bfeb.png" alt="Sun">
    <img src="https://i.ibb.co/z6PQ7qX/moon.png" alt="Moon">
  </div>
</header>
Oskar Grosser
  • 2,804
  • 1
  • 7
  • 18