Masonry List with Next.js Image Fill

I am encountering an issue where the normal HTML img tag works perfectly fine inside my Masonry List. However, when I use the Next.js Image Component with a layout of fill, it fails to render anything.

Custom Styles:

const ImageList = styled('ul', {
    columnCount: 3,
    columnGap: 10,
    display: 'block',
    listStyleType: 'none',
    overflowY: 'auto',
    padding: 0,
    margin: 0
})

const ImageListItem = styled('li', {
    position: 'relative',
    display: 'inline-block',
    lineHeight: 0,
    height: 'auto',
    marginBottom: 10
})

HTML Structure:

   <ImageList>
            {detailImage.map((image, idx) => {
                return (
                    <ImageListItem key={`_${idx}`}>
                        <Image
                            src={image.src}
                            alt={image.alt}
                            blurDataURL={image.blurDataURL}
                            placeholder={'blur'}
                            layout={'fill'}
                            objectFit={'cover'}
                        />

                        {/* <img
                            src={image.src}
                            style={{
                                width: '100%',
                                height: '100%',
                                objectFit: 'cover'
                            }}
                        /> */}
                    </ImageListItem>
                )
            })}
        </ImageList>

UPDATE: Since all images are being fetched from CMS and have specific width/height, I applied the padding-top technique to create a box and then utilized next/image with object-fit: cover.

Code Sample:

      <ImageListItem key={`_${idx}`}>
        <Box
          css={{
            display: 'inline-flex',
            pt: `${100 / (image.width! / image.height!)}%`
          }}
        >
          <Box css={{ position: 'absolute', inset: 0, m: 0 }} as={'figure'}>
            <Image
              src={image.src}
              alt={image.alt}
              blurDataURL={image.blurDataURL}
              placeholder={'blur'}
              layout={'fill'}
              objectFit={'cover'}
            />
          </Box>
        </Box>
      </ImageListItem>

Answer №1

For optimal functionality when using the layout='fill' attribute, it is crucial to have a parent container assigned to each image with the necessary style of position: relative;. Without this, the image may not display correctly due to missing width properties in its parent elements.

The following excerpt from the documentation elaborates on this concept:

When using fill, the image will expand to match both the width and height of the parent element, as long as the parent element has relative positioning. This method typically works best when combined with the objectFit property. To ensure proper rendering, make sure the parent element includes position: relative in its stylesheet.

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

Issue with CSS line height - Struggling to determine the precise number of lines

Despite finding an old post on this topic, the most popular answer and other solutions didn't work for many people. Even years later, I am still facing the same issue. My goal is to create a div that is precisely 19 lines tall (ideally aiming for 19. ...

What is the most dependable method for referencing a CSS class through programming?

Within my Sharepoint project, I am dynamically generating controls in the overridden CreateChildControls() method. I am uncertain which approach is more preferable when it comes to referencing the .css file: protected override void CreateChildControls() { ...

Is it possible to integrate Google AMP with a Ghost cms + Next.Js project?

Currently, I am working on integrating AMP into my blog posts within the framework of my Next.js project. The content for my blog is sourced from Ghost CMS and I am curious to know if it's possible to utilize AMP with these blog posts. Should I enable ...

NextJS Input Field causing a strange "Hydration Error indicating server HTML should not contain a <div> within a <form>", perplexingly occurring only in Chrome and exclusively on my personal computer

Looking for some assistance with a website I'm working on using NextJS and TailwindCSS. There seems to be a pesky little issue in my code that's causing some trouble. Below is the code snippet for the MainContent section of the page: "use c ...

What could be causing my navbar to not be responsive on mobile devices?

I'm in need of assistance. When viewing my website in mobile mode, the collapse hamburger menu is hiding too far to the right. This issue is making the site look unresponsive, and I've been unable to find a solution. It seems like the problem sta ...

Tips for including markdown content within components in MDX files

I'm currently in the process of utilizing MDX pages along with React components for a project. My issue lies in wanting to generate HTML when adding text inside a component, similar to how it works with content outside of components. However, I'v ...

Vanish Dropdown upon clicking Using JavaScript

Hey, I'm new to web development and I'm currently working on creating a web app for iPhone. Everything is going smoothly except for one issue - my dropdown menu works perfectly on desktop Chrome, but on the iPhone's Safari browser, I can&ap ...

Trying to figure out how to efficiently store data in an object within a multi-step survey using setState

I have a questionnaire with 20 questions and I'm attempting to save the responses in an object using the useState hook. I've been struggling with it for a while now. Here's a link to my CodeSandbox: https://codesandbox.io/s/radio-group-cont ...

Fetching data in a sequential manner within a Server Component to manipulate a consistent data set in Next.js

Recently diving into the world of next.js (utilizing v13 with App Router), I find myself in search of guidance regarding a particular challenge I've been wrestling with. My objective is to dynamically render data on a page and incrementally update it ...

The search functionality for the MongoDB module is not functioning properly within my Next.js application

Working on my nextjs application, I have encountered an issue with using the mongodb node module to find all documents in one of my collections. Despite successful usage of .findOne and .updateOne for other pages like login and password reset, when I use . ...

"Encountering an issue with Next.js due to npm dependencies importing CSS files

I am working on a next.js project and I am trying to incorporate a component from npm that internally imports typeface-montserrat. However, when trying to do so, Next.js is throwing an error: <path>/node_modules/typeface-montserrate/index.css:2 @fo ...

What is the best way to center an image and text vertically using bootstrap?

I'm currently working on a Bootstrap website and have reached a section where I want to display text on the left and an image on the right. While I've managed to achieve this layout, I'm struggling with vertically centering the image. Despit ...

What could be causing the preloader to fail in my React application?

I am developing a React App with Redux functionality, and I am looking to implement a preloader when the user clicks on the "LoginIn" button. To achieve this, I have created a thunk function as follows: export const loginInWithEmail = (email, password) =&g ...

Node.js - Utilize the filesystem module to generate an array of objects from files

Currently, I am in the process of developing a menu for my ReactApp that mirrors a folder structure. Each folder is categorized based on the documents it contains, with some folders having sub-folders and files nested within them. The desired output shoul ...

What is the best way to decouple the data layer from Next.js API routes?

Currently, I am working on a project using Next.js with MongoDB. My setup involves using the MongoDB client directly in TypeScript. However, I have started thinking about the possibility of switching to a different database in the future and how that would ...

Turn off the extra space inserted by DataTables

Help needed with centering table header text. <table class="table table-bordered table-hover center-all" id="dataTable"> <thead> <tr> <th scope="col" style="text-align: center">Nam ...

Troubleshooting problems with spacing in CSS flexbox due to the gap property

Having some trouble with flexbox. The gap property is making the columns too wide when trying to create a simple 3 column row. I was under the impression that the gap value should not affect the width set. For example, using flex: 0 1 33.33% and gap 2rem ...

What steps are involved in making select fields that change dynamically?

There are two fields available for the user to interact with: size and design. Users have the ability to add more instances of these fields as many times as they desire. Illustration: If I choose M for the size, it will display in the console: https://i ...

The jQuery script is functioning flawlessly in one specific direction

Currently, I am utilizing a basic script to alter the color of elements based on the div being hovered over. While this works smoothly in one direction down the line, when trying to reverse order and backtrack, the colors do not function as intended. The ...

Utilize a unique font exclusively for Internet Explorer

I am encountering a significant issue trying to utilize custom fonts in Internet Explorer. Currently, I have implemented a specific font using @font-face and it works perfectly in modern browsers but fails to render properly in IE. The method I am curren ...