Ensure the Next/Image component fits neatly inside a div without distorting its aspect ratio, and keep the

I've been attempting to style a NextJS image in a way that it has rounded corners, expands to fit its container div (which is blue in the image), and maintains its aspect ratio (only known at runtime). However, what I currently have is not working as expected - the image does not receive the border-radius, but rather the surrounding box (depicted in black on the image) receives it. I'm struggling to find a solution that allows the dynamic image size while still applying the border radius. Another factor to consider is that all of this is happening within a fixed-positioned div (shown in red on the image) that encompasses the entire popup.

https://i.stack.imgur.com/eneSH.png

I've tested the code snippet below based on recommendations from other sources, and although it almost works, the issue remains with the image not getting the desired rounded corners because the box around it is larger than the content, resulting in rounding the box instead of the image itself.

{/* Card that shows on click */}
            <div className='fixed z-10 w-full h-full left-0 top-0 invisible bg-black/[.6]' id={'hidden-card-' + title} onClick={hideEnlargement}>
                <div className='w-[80%] h-[80%] translate-x-[calc(50vw-50%)] translate-y-[calc(50vh-60%)] rounded-2xl'>
                    <Image
                        src={img} 
                        alt={alt}
                        quality={100}
                        className="rounded-2xl bg-black m-auto"
                        fill={true}
                        style={{"objectFit" : "contain"}}
                    />

                </div>
                
            </div>

Answer №1

Here are some simple adjustments to make this code work:

  1. Replace w-full h-full left-0 top-0 with inset-0 for brevity. This sets all margins to 0.
  2. In the wrapper div for your image, round the corners and set overflow to hidden. Remove the translate-x class as well. Use h-3/4 and w-3/4 for 75% width and height.
  3. Set your image's height and width to 100% with an object-fit of cover. Cover fills the space without cropping, while fill will crop the image if necessary.
<div
  className="fixed inset-0 z-10 bg-black/[.6]"
  id={'hidden-card-' + title}
  onClick={hideEnlargement}
>
  <div className="rounded-2xl overflow-hidden h-3/4 w-3/4 m-auto translate-y-[calc(50vh-50%)]">
  <Image
    src={img}
    alt={alt}
    quality={100}
    className="bg-black w-full h-full object-cover"
    fill={true}
    />
  </div>
</div>

Check out the Stackblitz demo

Edit

To prevent cropping and maintain rounded corners and aspect ratio, pass width and height properties to the Next/Image component. Otherwise, set the fill prop to true.

The fill prop absolutely positions the image, eliminating natural flow. To avoid this, provide image dimensions in the props.

Below is an example modal structure:

// Assuming you pass props with img containing
// src, alt, width, and height
<div
  className="fixed inset-0 z-10 bg-black/[.6] grid place-content-center"
  onClick={closeModal}
>
  <Image
    src={img.src}
    alt={img.alt}
    width={img.width}
    height={img.height}
    quality={100}
    className="max-w-[95vw] max-h-[95vh] rounded-2xl animate-bounceIn"
  />
</div>

This approach centers everything using grid place-content-center. No need for extra transformations or margins. Set max-width and max-height to constrain the image within the viewport. However, disparity between actual size and constrained size may occur. Using object-fit: contain can fix this, albeit at the cost of losing rounded corners.

You could alternatively manually optimize images and use img or picture tags.

Explore the new Stackblitz Demo

The updated demo includes various images with different dimensions. Data structure is shown in the pages/api/images.js file. The new "modal" component is located in the `pages/components/Modal.js file.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am planning to divide my web application into two sections by utilizing react router. I intend to incorporate a router within one of the routes mentioned earlier

/src |-- /components | |-- /signin | |-- SignIn.js | |-- /home | |-- Home.js | | |-- /dashboard | |-- Dashboard.js | |-- /assignee |-- /App.js |-- /index.js Dividing the project into two main parts: signi ...

Basic HTML Audio Player Featuring Several Customizable Variables

I have a unique API that manages music playback. Instead of playing audio in the browser, it is done through a Discord bot. Achievement Goal https://i.stack.imgur.com/w3WUJ.png Parameters: current: indicates the current position of the track (e.g. 2:3 ...

Using ReactJs Component to interact with Laravel Api and retrieve uploaded images

I need assistance retrieving my list from the Laravel API. I have successfully fetched the list details, but I am encountering difficulties fetching details with images. My card.js component import React, {useState, useEffect} from 'react'; imp ...

Button Click Not Allowing Webpage Scroll

I am currently in the process of developing a website that aims to incorporate a significant amount of motion and interactivity. The concept I have devised involves a scenario where clicking on a button from the "main menu" will trigger a horizontal and ve ...

Eliminating the glow effect, border, and both vertical and horizontal scrollbars from a textarea

Dealing with the textarea element has been a struggle for me. Despite adding decorations, I am still facing issues with it. The glow and border just won't disappear, which is quite frustrating. Could it be because of the form-control class? When I rem ...

Making the browser refresh the CSS automatically once it has been modified

When updating a CSS file on the server, it's common for many client browsers to continue loading pages using the old cached CSS file for an extended period. After exploring various posts and piecing together different ideas, I have devised what appea ...

Modify the class of rows in table 2 once a particular value of a radio button in table 1 has been selected

One issue I am facing is related to two tables with radio buttons. Each table highlights the corresponding row when a radio button is checked, working independently. However, I need a specific value from table 1 to un-highlight any previously checked rows ...

Creating a proxy using the Next.js API is not compatible with the next-http-proxy-middleware package

I'm attempting to create a proxy using the Next.js API, but it appears to be malfunctioning. This is how my pages/api/index.js file looks: import { NextApiRequest, NextApiResponse } from 'next'; import httpProxyMiddleware from 'next-ht ...

What is the best way to display the L.featureGroup using an array of coordinates?

Is there a way to render the L.featureGroup using an array of coordinateRoute from the data.json file, and then trigger it with a button labeled "Snake it!"? Essentially, I want to be able to click on "snake it!" which will have its own unique id, causing ...

Invoke a method from a related component within the same hierarchy

Imagine this scenario: You're working on a reusable item carousel. The slide track component and the slide navigation component need to be independent and in a sibling relationship so you can position the buttons wherever you want. But how do you trig ...

issue with using references to manipulate the DOM of a video element in fullscreen mode

My current objective is to detect when my video tag enters fullscreen mode so I can modify attributes of that specific video ID or reference. Despite trying various methods, I have managed to log the element using my current approach. Earlier attempts with ...

React: An error has occurred - Properties cannot be read from an undefined value

THIS PROBLEM HAS BEEN RESOLVED. To see the solutions, scroll down or click here I've been working on a React project where I need to fetch JSON data from my server and render it using two functions. However, I'm encountering an issue where the v ...

What are some techniques I can use to ensure my image grid is responsive in html/css?

If you want to check out the website, you can visit . The main goal is to create an image grid for a portfolio. It appears really nice on a 1080p screen, but anything below that seems messy and unorganized. Any assistance or suggestions on how to improve ...

Troubleshooting Cross-Origin Resource Sharing (CORS) issue when making a GET request

My application utilizes ASP.Net Core Web Api as the backend service. For the frontend, I have integrated React along with making requests to the backend API using axios. export const overviewGet = (orderId: string): Promise<IOrder> => { const U ...

Guide on retrieving POST data in sveltekit

Hello, I'm new to sveltekit and I am trying to fetch post data in sveltekit using a POST request. Currently, I am utilizing axios to send the post data. const request = await axios .post("/api/user", { username, email, ...

Why isn't the hover function working on the table row element?

When I try to apply a hover effect on tbody and td elements, it works perfectly. However, when I apply the same effect to the tr element, it doesn't work as expected. I am using inline style (js pattern) rather than CSS code and incorporating Radium i ...

Transitioning a substantial React application to Next.js specifically to enhance social sharing capabilities and optimize for SEO through server-side rendering

I have successfully built and launched a ReactJS app with separate front and backend (Laravel). One issue I am encountering is the difficulty in sharing pages with dynamic data because React cannot generate meta tags dynamically, resulting in no dynamic p ...

What is the best way to increase the size of this text when an image is hovered over?

I'm looking to make the .thumb_text element grow when hovering over the <img> within the li.thumb_list. Currently, I can only achieve this effect when hovering over the text itself, not the image. In addition, the text is inexplicably becoming ...

Leveraging the power of `useDispatch` and `connect`

When it comes to dispatching actions in react-redux, I've noticed that both useDispatch and connect are available options. However, I'm curious about whether I can exclusively use useDispatch to handle store data throughout my entire react app. A ...

The magic of coding is in the combination of Javascript

My goal is to create a CSS animation using jQuery where I add a class with a transition of 0s to change the color, and then promptly remove that class so it gradually returns to its original color (with the original transition of 2s). The code below illus ...