Search code examples
csssassflexboxobject-fit

CSS positioning of off-center image


I need to center the mobile phone. Here is what is included in the mockup: enter image description here

However, this is what I'm getting: enter image description here

How can I position/center the mobile image so that the shadow doesn't push the phone to the right? I'm using display: flex;

HTML

<div class="image">
        <img src="<?php echo esc_url( get_stylesheet_directory_uri() ); ?>/assets/images/landing-page/mobile-image-1.jpg" alt="">
        <img src="<?php echo esc_url( get_stylesheet_directory_uri() ); ?>/assets/images/landing-page/mobile-image-2.jpg" alt="">
        <div class="middle-image">
             <img class="middle-image-mobile" src="<?php echo esc_url( get_stylesheet_directory_uri() ); ?>/assets/images/landing-page/mobile-image.png" alt="">
        </div>
        <img src="<?php echo esc_url( get_stylesheet_directory_uri() ); ?>/assets/images/landing-page/mobile-image-3.jpg" alt="">
        <img src="<?php echo esc_url( get_stylesheet_directory_uri() ); ?>/assets/images/landing-page/mobile-image-4.jpg" alt="">
</div>

CSS

& .image {
        display: flex;
        flex-flow: row nowrap;
        justify-content: space-around;


        & > img {
            border-radius: var(--theme-border-radius);
            flex-grow: 1;
            height: 100%;
            width: 13%;
        }
}

Solution

  • Have a look, please. I tried to create something similar. That is with the assumption that you have added white space to the picture so that the image together with the shadow looks centered.

    .wrapper {
     display: flex;
     justify-content: space-around;
     border: 5px solid gray;
     width: 650px;
     height: 300px;
     margin: auto;
    }
    .blocks {
     position: relative;
     width: 13%;
     height: 100px;
     background-color: #d5d5d5;
     margin: 10px;
    }
    .blocks:not(:nth-child(3)) {
      border-radius: 10px;
      box-shadow: 0 3px 12px -6px black;
      border: 5px solid white;
    }
    .blocks:nth-child(2), .blocks:nth-child(4) {
     top: 100px;
    }
    .blocks:nth-child(1), .blocks:nth-child(5) {
     height: 150px;
    }
    .center {
     position: relative;
     z-index: -1;
     top: 10px;
     display: block;
     margin-left: -30px;
     margin-right: -30px;
     width: 150px;
     height: 250px;
     border-right: 30px solid #9696d8;
     border-left: 30px solid #9696d8;
    }
    <div class="wrapper">
      <div class="blocks"></div>
      <div class="blocks"></div>
      <div class="blocks center"></div>
      <div class="blocks"></div>
      <div class="blocks"></div>
    </div>

    You can see I used negative margins to bring elements closer to the element that is in the center. If you wanted to deal with the overlaying images then you would add z-index depending on what needs to be in front.

    Hope it helps.