Search code examples
htmlcssimageresponsivecss-grid

Centered text overlay on image that is object-fit & object-position (CSS GRID)


I'm wondering if it's possible to have a centered text overlay (caption) on an image that is object-fit: contain; AND object-position: left top; (ie. not centered)

Image is being displayed in CSS Grid. (Display: Grid;)

Example of what I'm trying to do:

Example

*********** ANOTHER EXAMPLE: I would also like to be able to do centered captions for portrait ratio images ***********

.container {
  height: 40vw;
  width: 40vw;
  border: 1px solid black;
  display:grid;
}

img {
  max-width: 100%;
  max-height:100%;
  height: 100%;
  width: 100%;
  object-fit: contain;
  object-position: left top;
}
<div class="container">
  <img src="https://ichef.bbci.co.uk/news/660/cpsprodpb/A825/production/_103954034_gettyimages-990971906.jpg">
</div>

Thank you in advance!


Solution

  • object-fit controls how replaced content fits within its container. You do not have access to the replaced content in terms of layout and positioning. A way to achieve the effect you're wanting within a grid would be to add a new container, set some width/height attributes on your image based on the container values and then position your text relative to that image, avoiding the use of Object Fit.

    .container {
      align-items: start;
      height: 40vw;
      width: 40vw;
      border: 1px solid black;
      display:grid;
    }
    
    img {
      display: block;
      height: auto;
      margin: 0 auto;
      max-height: 40vw;
      max-width: 40vw;
    }
    
    .textcontainer {
      position: relative;
    }
    
    .textcontainer-x-text {
      color: limegreen;
      font-family: sans-serif;
      font-weight: bold;
      left: 50%;
      position: absolute;
      text-align: center;
      text-transform: uppercase;
      top: 50%;
      transform: translate(-50%, -50%);
    }
    <p>Portrait</p>
    <div class="container">
      <div class="textcontainer">
        <div class="textcontainer-x-text">Example Text Which Could Be Long</div>
        <img src="http://placehold.it/150x400">
      </div>
    </div>
    
    <p>Landscape</p>
    <div class="container">
      <div class="textcontainer">
        <div class="textcontainer-x-text">Example Text Which Could Be Long</div>
        <img src="http://placehold.it/300x150">
      </div>
    </div>
    
    <p>Square</p>
    <div class="container">
      <div class="textcontainer">
        <div class="textcontainer-x-text">Example Text Which Could Be Long</div>
        <img src="http://placehold.it/300x300">
      </div>
    </div>