0

I'm trying to create a "hover to reveal content" div
Like this:

html {
  margin: 0;
  height: 100%;
  min-height: 100%;
}

body {
  margin: 0;
  height: 100%;
  min-height: 100%;
  background-color: red;
}

hr {
  transition: width 1s;
  width: 5rem;
  margin: 0 auto 0 auto;
}

#container {
  width: 50%;
  height: 100%;
  padding: 5rem;
  background-color: white;
  margin: auto;
}

.expand {
  width: 100%;
  height: 1rem;
  padding: 1rem 0 1.1rem 0;
  background: inherit;
  transition: height 0.5s;
  text-align: center;
}

.wrapper:hover>.expand {
  height: auto;
}

.wrapper:hover>hr {
  width: 100%;
}

.text {
  margin: 1rem 0 0 0;
  overflow: hidden;
  height: 0;
  transition: height 0.5s;

}

.wrapper:hover .text {
  height: 16rem;
  transition: height 1s;
}
<div id="container">
<div class="wrapper">
  <hr>
  <div class="expand">
    Hover to Learn more
   <div class="text">
       Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
   </div>
  </div>
  <hr>
  </div>
</div>

But I'm facing a few problems:
  1. As you can see when running the sample code it opens perfectly but when hovering out of the div there is no closing transition

  2. I have to manually add a value height:16rem instead of automatically assigning the height required

    .wrapper:hover .text {
      height: 16rem;
      transition: height 1s;
    }
    

    (this becomes and issue when the browser is resized)

my best guess is that both the issues arise because of the height:auto source
so I'm guessing it's almost impossible to fix via css but is there any javascript solution (ideally using Vanilla js)?

cak3_lover
  • 1,440
  • 5
  • 26

1 Answers1

0

One way I have worked around this exact challenge was to avoid trying to transition a dynamic element's height. You can still achieve a similar 'feel' by using something like:

.wrapper {
  transition: transformY(0);
  opacity: 0;
  height: 0;
}
.wrapper:hover {
  transition: transformY(10px);
  height: auto; // Don't animate this property
  opacity: 1;
}
James
  • 115
  • 6
  • well this approach looks visually horrible so I'm trying to avoid it, do you have any other solution? :P – cak3_lover Mar 24 '21 at 08:42
  • Horrible is in the eye of the beholder. If you insist on this approach then you will have to use javascript. Start by looking into `offsetHeight`, and using this to build CSS to suit (append it to the `document`). You will need to reconstruct this CSS when the element changed shape (ie browser resize). – James Apr 07 '21 at 03:07