Search code examples
cssbackground-image

Stretch section to height of background image


I'm using bootstrap, although the example doesn't consider it.

What I need is that the section stretches to the height of the background image.

I've built a minimal example, but it doesn't seem to load background images:

https://codepen.io/lib0/pen/zYxyoLd


Solution

  • So it is a different apporach to what you've taken and I've followed this example CSS: How to set container size equal to background image size . It doesn't use the background-image property though. I'm not sure if that is a necessity for you.

    HTML

    <div class="wrap">
        <img src="https://escolaeducacao.com.br/wp-content/uploads/2015/07/dna.jpg" />
    
        <section class="content">
        to be expanded to the size of the background image.
        </section>
    
    </div>
    

    CSS

    .wrap {
        display: inline-block;
        position: relative;
    }
    
    .wrap img + .content {
        position: absolute;
        top: 0;
        left: 0;
    }
    

    Setting the wrap to position: relative will cause child elements that are set to position: absolute to position itself in relation to that parent element