Search code examples
htmlcssimageposition

Text And Button in Full Width Image


I have a page wherein I have multiple full-width <img>'s - I have to add a <button> and <h2> overlaid upon each image. Images will have variable heights, so elements within need to conform to the perimeter set by their width + height.

An image is styled thus:

CSS

.FullWidthImg {
   width: 100vw;
   position: relative;
   left: 50%;
   right: 50%;
   margin-left: -50vw;
   margin-right: -50vw;
}

HTML

<div id="container"> <!--ONLY STYLING FOR container IS position: relative-->
  <img src="xx" alt="xx" style="FullWidthImg"/>
  <h2>TEXT GOES HERE</h2>
  <button>i'm a button</button>
</div>

Most approaches suggest styling <h2> and <button> with position: absolute - this works if you have one image element and the image always has the same height, however neither is the case for me.

Another approach I've seen is making something like:

<div style="background-image: url(/img.com)">
  <h2>TEXT GOES HERE</h2>
  <button>i'm a button</button>
</div>

... And then positioning elements within, which could work but I'd like to avoid in-line styling if possible.

Are there any alternative approaches that would work for this use-case?


Solution

  • Building off your first suggestion, here's how you could accomplish your desired layout without inline styles.

    .img-wrapper {
      position: relative;
    }
    
    .img-wrapper img {
      width: 100%;
    }
    
    .img-wrapper .overlay {
      position: absolute;
      top: 0; left: 0; right: 0; bottom: 0;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      text-align: center;
    }
    
    .img-wrapper h2 {
      margin: 0 0 .5em;
    }
    <div class="img-wrapper">
      <img src="http://via.placeholder.com/600x150/eee/ddd" />
      <div class="overlay">
        <h2>Heading</h2>
        <button>Button</button>
      </div>
    </div>
    
    <div class="img-wrapper">
      <img src="http://via.placeholder.com/600x400/eee/ddd" />
      <div class="overlay">
        <h2>Heading</h2>
        <button>Button</button>
      </div>
    </div>