Addy
Addy

Reputation: 49

Text appear from left to right

I want the caption of a image (which is not necessary is a real caption) appear when the image is hovered. The text should appear from left to right so it's container should grow on the X axis as the image is hovered. I have been able to make the text appear on hover but the transition effect is where I am stuck.
This is what I have tried:

CSS:

.morbid {
  display: none;
  margin-left:10px;
}

a:hover + .morbid {
  position:relative;
  display: block;
}

HTML:

<a>
  <img src='.../goals/sia.png'> 
</a>
<div class="morbid">
This text will appear as you hover your mouse over the image.
</div>

Actually the whole div must grow, text remaining static and I want the text to be hidden unless the image is hovered.

Upvotes: 2

Views: 8613

Answers (2)

Harry
Harry

Reputation: 89750

You cannot transition the display property's change of value. The full list of properties which can be animated is available in the spec.

For the content to grow and appear you need to transition the max-width (or width, if you can set a fixed width to the element) like done in below snippet.

.morbid {
  width: auto;
  max-width: 0%;
  white-space: nowrap;
  overflow: hidden;
  transition: max-width 1s linear;
}
a:hover + .morbid {
  max-width: 100%;
}
<a href="#">
  <img src='http://picsum.photos/400/200'>
</a>
<div class="morbid">
  This text will appear as you hover your mouse over the image.
</div>

JSFiddle


Alternately, if you want the text to grow from the center then you can make use of absolute positioning with transform like in the below snippet.

.container {
  position: relative;
  width: 400px;
}
.morbid {
  position: absolute;
  left: 50%;
  max-width: 0%;
  white-space: nowrap;
  overflow: hidden;
  transform: translateX(-50%);
  transition: max-width 1s linear;
}
a:hover + .morbid {
  max-width: 100%;
}
<div class="container">
  <a href="#">
    <img src='http://picsum.photos/400/200'>
  </a>
  <div class="morbid">
    This text will appear as you hover your mouse over the image.
  </div>
</div>

JSFiddle

Upvotes: 12

RndmGuy94
RndmGuy94

Reputation: 41

Use the transition property on the element you want to add a transition effect.

Make the caption grow and shrink in size:

CSS:

.morbid {
    /* display: none; */
    margin-left:10px;
    opacity: 0;
    font-size: 12pt;
    -webkit-transition: font-size 0.25s;
    transition: font-size 0.25s;
}

a:hover + .morbid {
    position:relative;
    /* display: block; */
    font-size: 16pt;
    opacity: 1;
}

HTML:

<a>
    <img src='.../goals/sia.png'> 
</a>
<div class="morbid">
    This text will appear as you hover your mouse over the image.
</div>

I had to change opacity for the caption instead of changing the display property because the animation doesn't show when changing the display property.

Upvotes: 1

Related Questions