Search code examples
csssvgflexboxobject-fit

Achieving an Overlapping image in a flex container with object-fit


Hey there i have asked a similar question before and was able to achieve it , the thing is that i had to use a png image, the downside is that its way too big.

After some research i found a method using a svg container and a alpha and beta channel of the image.

However the main difficult i ran into is to get object-fit working so the image will always cover the full 50% of its flexbox container... is that even possible? what am i missing..thanks a lot.

Effect i am trying to achieve

https://codepen.io/HendrikEng/pen/RVzYoR?editors=0100

.c-hero {
   align-items: center;
  display: flex;
  flex-direction: row;
  justify-content: center;
  background: grey;
  height: 30px * 15;
  text-align: center;

  &__image {
    display: flex;
    margin-bottom: -60px;
    margin-top: 60px + 19px;
    max-height: 682px;
    min-height: calc(100% + 140px);
    object-fit: cover;
    object-position: top;
    width: 50%;
  }

  &__item {
    align-self: center;
    width: 50%;
    }
}

<section>
  <div class="c-hero">
    <svg class="c-hero__image" preserveAspectRatio="xMinYMin" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
        <defs>
            <mask id="transparentmask">
                <image width="100%" height="100%" xlink:href="http://i.imgur.com/n080w42.png"></image>
            </mask>
        </defs>
        <image mask="url(#transparentmask)" width="100%" height="100%"  xlink:href="http://i.imgur.com/LTgnz9E.jpg"></image>
    </svg>
    <div class="c-hero__item">
      <p>Lorem Ipsum</p>
    </div>
  </div>
</section>

Solution

  • Please put the following css to your codepen:

    /**
    * @define c-hero; weak
    */
    
    .c-hero {
      align-items: stretch;
      display: flex;
      flex-direction: row;
      justify-content: center;
      background: grey;
      height: 28.45vw;
      text-align: center;
    
      &__image {
       flex: 1 0 auto;
       min-height: 130.96%;
      }
    
      &__item {
        align-self: center;
        width: 50%;
      }
    }