How can I seamlessly grow/shrink elements on hover using CSS?

Viewed 808

I'm very new to coding and I just want to do something basic in CSS. I have a landing page which is split into two down the middle. On the left side, is a yellow div. On the right side, a grey div. When I hover over a div, it increases its width (ltr for the left div and rtl right div). On the same hover event I want the OTHER div to decrease its width. So there's no overlap between the two.

With the code I have the left side div works. The hover event also works. When I hover over the left side. The width goes up to 51% and the right side div's width becomes 49%. However, the right side equivalent doesn't work. When I hover over the right side. The right side div increases its width but the left side div does not decrease dwn to 49%. The right side just overlaps the left.

Any ideas? I found some answers about parent/child relationships and played around but with no success.

Apologies for my poorly written code. I am only starting out and would appreciate some advice.

#leftside {
  /*this is the orange half*/
  height: 100%;
  width: 50%;
  position: absolute;
  left: 0;
  top: 0;
  opacity: 0.5;
  background-image: linear-gradient(rgba(255, 255, 0, 1), rgba(255, 165, 0, 1));
  transition: all 1s;
}

#leftside:hover {
  opacity: 1.0;
  width: 51%;
}

#leftside:hover+#rightside {
  width: 49%
}

#rightside {
  /*this is the grey half*/
  height: 100%;
  width: 50%;
  position: absolute;
  right: 0;
  top: 0;
  opacity: 0.5;
  background-image: linear-gradient(rgba(255, 255, 255, 0), rgba(160, 160, 160, 1));
  transition: all 1s;
}

#rightside:hover {
  opacity: 1.0;
  width: 51%;
}

#rightside:hover+#leftside {
  width: 49%
}
<div id="leftside">
  <a class="leftsidehome" href="page1.html"></a>
</div>
<div id="rightside">
  <a class="rightsidehome" href="page2.html"></a>
</div>

1 Answers

The problem with your code is #rightside:hover+#leftside because CSS cannot look back. Below a possible solution using flexbox.

.container {
  display: flex;
  width: 100%;
}

#leftside,
#rightside {
  flex-grow: 1; /* Allow each flex item to grow */
  flex-shrink: 1; /* Allow each flex item to shrink */
  width: 50%;
  height: 100px; /* Used only to make them visible */
  transition: width 1s; /* Animate the change of width */
}

#leftside {
  background: yellow;
}

#rightside {
  background: grey;
}

#leftside:hover {
  width: 51%;
}

#rightside:hover {
  width: 51%;
}
<div class="container">
  <div id="leftside">
    <a class="leftsidehome" href="page1.html"></a>
  </div>
  <div id="rightside">
    <a class="rightsidehome" href="page2.html"></a>
  </div>
</div>

Related