Home > Software design >  How to make square image container with css grid
How to make square image container with css grid

Time:09-30

I want to make a modal with a image and other elements to the right, something like this: enter image description here I tried making the modal content as a grid with two columns, the problems is when I try to adjust the image to fill all the avaiable space in the modal content, it overflows like this: enter image description here My css code looks like this:

  <div class="modal">
        <div class="content">
            <div class="frame">
                <img src="https://picsum.photos/400" alt="Example">
            </div>
            <div class="text">
                Lorem ipsum, dolor sit amet consectetur adipisicing elit. Quis est mollitia possimus omnis nisi quo
                aliquid ad accusantium dignissimos corrupti. Impedit, asperiores magnam corporis iste possimus tempore
                quisquam provident dicta. Lorem ipsum dolor sit, amet consectetur adipisicing elit. Quibusdam
                consequuntur, incidunt hic dolorum tempora inventore id sint ullam magnam veniam eveniet vitae, harum
                dolorem tenetur libero voluptate voluptatibus. Inventore, excepturi!
            </div>
        </div>
    </div>

.modal {
    position: fixed;
    height: 100%;
    width: 100%;
    background-color: rgba($color: #000000, $alpha: 0.6);
    display: grid;
    place-items: center;
}

.content {
    background-color: $color-white;
    width: 60%;
    height: 600px;
    border-radius: 5px;
    display: grid;
    grid-template-columns: auto 300px;
}

.frame > img {
    width: 100%;
    max-height: 100%;
    object-fit: cover;
}

.text {
    padding: 2rem 1rem;
}

The modal I tried to do has the problem of the image overflow. I setted the container div to grid with two columns, but the image column overflows the container as we can see in the picture. I want the image to take the space avaiable in the container but maintaining the 1 : 1 aspect ratio, also to be responsive, when the user change the screen size the image always has to maintain the 1:1 aspect ratio and not crop the image.I setted the height as static pixels because I want to add a element with a scrolling bar that otherwise will overflow or expand the container if its height was declared as percentages.

CodePudding user response:

Just specify a max-height to the container(.frame) it will start working fine for 1:1 images because max-height:100% doesn't mean anything if you don't specify a height for its parent

and if you want to work for any ratio then remove the width property from the .frame > img because if you don't specify a width it will adjust itself according to it's height

CodePudding user response:

I think the easiest way would be to use css aspect-ratio like this:

img {
   width: 100%;
   aspect-ratio: 1;
}

you can read more about it here

  • Related