user3064626 user3064626 - 3 months ago 7
CSS Question

Dynamically adjust height of div with transition over image

I have an image description appear on hover. I make it transition up by changing the margin-top value. The problem is I want it to be able to take as much text as possible but still have everything appear over the image.

Here is a demo on JsBin.

Answer

Instead of using margin-top to animate, use transform property to do it using something like this:

.description {
  text-align: center;
  position: absolute;
  width: 100%;
  transition: transform 200ms ease-in;
  color: white;
  background: black;
  opacity: 0.6;
}
.myslider:hover .description {
  transform: translate(0, -100%);
}

and there you go! Cheers!

.myslider {
  overflow: hidden;
  position: relative;
  max-width: 400px;
}
.myslider img {
  width: 100%;
  display: block;
}
.title {
  position: absolute;
  width: 100%;
  height: 20px;
  padding-bottom: 2px;
  margin-top: -20px;
  transition: margin-top 200ms ease-in;
  background: black;
  opacity: 0.6;
}
.title-text {
  color: white;
  float left;
  padding-left: 5px;
}
.nav-buttons {
  background: white;
  float: right;
  padding: 0px 5px 0px 5px;
  border: 1px solid black;
  margin: 0px 5px 0px 0px;
  cursor: pointer;
}
.myslider:hover .title {
  margin-top: 0px
}
.description {
  text-align: center;
  position: absolute;
  width: 100%;
  transition: transform 200ms ease-in;
  color: white;
  background: black;
  opacity: 0.6;
}
.myslider:hover .description {
  transform: translate(0, -100%);
}
<div class="myslider">
  <div class="title">
    <span class="title-text">Image 1 </span>
    <span class="nav-buttons"> &gt; </span>
    <span class="nav-buttons"> &lt; </span>
  </div>
  <img src="http://placekitten.com/400/400">
  <div class="description">Image Caption: Should accept as much text as posisble. more text, more text, more text</div>
</div>

Also made some minor changes:

  1. Used &lt; and &gt; for correct XHTML syntax

  2. Added display: block to the image to remove the small whitespace below the image.