beta beta - 4 months ago 14
HTML Question

Image + Text in DIV and keep aspect ratio

I have the following requirements:


  • I need a
    div
    with an image + text inside.

  • The
    div
    should keep its aspect ratio and all images inside of the
    divs
    should have the same height (to do this, I use: Maintain the aspect ratio of a div with CSS).

  • The image inside of the
    div
    should be stretched in order to completely fill the parent
    div
    .



I prepared a jsfiddle

I have two main issues:


  • As you can see, the left
    div
    is higher, because it has text inside. This collides with the
    padding-bottom: 150%
    -approach which is used to preserve the aspect ratio of the
    divs
    when their size is changed. The goal, however, is that all
    divs
    have the same size no matter if/how much text they have inside.

  • Moreover, I would like to change the opacity of the background image when I hover the div. However, the text-opacity should not change. I think this can only be achieved via JS. How?


Answer

Add text as position:absolute

.inner-text{
  position:absolute;
  width:100%;
  height:100%;
  text-align:center;
  z-index:1;
}
.event:hover .inner-text{
  background:rgba(255,255,255,0.5)
}


<div class="bit-3">
  <div class="event" style="background-image: url(https://container25.at/wpdev/wp-content/uploads/2016/06/test.jpg)">
  <div class="inner-text">
      Text inner
  </div>
  </div>
</div>

Update fiddle code: https://jsfiddle.net/f5uxz4mx/8/

Comments