Scale div to background-image height

前端 未结 2 1018
野的像风
野的像风 2021-01-28 07:58

I\'ve got a page using a background-image. background-size is set to cover.

The content is just a heading and two buttons. I want the div to b

相关标签:
2条回答
  • 2021-01-28 08:23

    You can use one same image file for both background and inline, and set the inline image to visibility: hidden; (keep space), so the div can automatically resize based on the image size.

    There is no way to detect the background image size with CSS.

    .container {
      background: url("https://picsum.photos/600/150?image=0") 0 0 no-repeat;
      background-size: cover;
      position: relative;
      border: 1px solid red;
      overflow: hidden;
    }
    
    .image {
      visibility: hidden;
    }
    
    .title {
      position: absolute;
      width: 100%;
      background: rgba(255, 255, 255, .5)
    }
    <div class="container">
      <div class="title">Hello</div>
      <img class="image" src="https://picsum.photos/600/150?image=0">
    </div>

    0 讨论(0)
  • 2021-01-28 08:23

    know this is old thread but stumbled upon it.

    the following works for me if i know the dimensions of the image,

    eg. 1220x404 => 1220/404 = 3.01980198 = 30.1980198

    header { max-height: 404px; height: 30.1980198vw; }
    
    0 讨论(0)
提交回复
热议问题