Achieving fixed width and automatic height for images in Next JS: a guide

I am struggling to showcase a list of images with a fixed width while utilizing the original image height set at 100%. A similar inquiry can be found here, yet it remains unanswered.

I have gone through the responses shared here and attempted them. The images exist in the DOM, but they are off-screen and fail to display.

The dimensions of the images vary e.g., 1280x15141, 1280x14333. Following the example from the docs link.

    <main className="mx-auto max-w-7xl ">
      <section className="flex flex-col">
        {chapter.images.map((img) => (
          <div key={img} style={{ position: 'relative', width: '768px', height: '100%' }}>
            <Image alt="Mountains" src={img} layout="fill" objectFit="contain" />
          </div>
        ))}
      </section>
    </main>

No image appears on the display even though they are present in the DOM.

https://i.sstatic.net/s4zjB.png

Update: Based on recommendations, I included a height.


      <section className="flex flex-col">
        {chapter.images.map((img) => (
          <div key={img} style={{ position: 'relative', width: '768px', height: '100px' }}>
            <Image alt="Mountains" src={img} layout="fill" objectFit="contain" />
          </div>
        ))}
      </section>

https://i.sstatic.net/N4vWK.png

Alternatively, using a plain img tag approach. When employing the images within <img> tags, I manage to witness the image while setting the width along with the default height.

      <section className="flex flex-col gap-2">
        {chapter.images.map((img) => (
          <div key={img} className="mx-auto md:w-4/5">
            <img alt="Mountains" src={img} />
          </div>
        ))}
      </section>

Nevertheless, my intention is to leverage NextJs Image component. How may I achieve this?

Answer №1

It seems that your file path for the import is not correct

import mountains from '../../public/mountains.jpg'

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

Unable to resolve 500 error on Vercel in Next.js despite successful local development

Here is the content of route.ts import fs from 'fs'; import path from 'path'; import PizZip from 'pizzip'; import Docxtemplater from 'docxtemplater'; import { NextRequest, NextResponse } from 'next/server'; ...

Oops! Looks like we are having trouble accessing properties of an undefined value when trying to read the 'map' property

Encountering an issue with rendering a React page using NextJS hooks. The error message indicates that there is an attempt to read properties of undefined during mapping, possibly due to the object being empty or undefined on initial load. I have added "?" ...

Is it possible to utilize global variables within CSS properties?

I have a scenario where I need to dynamically change values in an animation. The line of code that needs modification is: clip-path: polygon(var(clip1) 0, 100% 1%, 100% 100%, 50% 100%); let root = document.documentElement; root.style.setProperty('c ...

Getting Session from Next-Auth in API Route: A Step-by-Step Guide

When printing my session from Next Auth in a component like this, I can easily see all of its data. const session = useSession(); // ... <p>{JSON.stringify(session)}</p> I am facing an issue where I need to access the content of the session i ...

Box-sizing:border-box causing CSS padding problem in Firefox

Something strange is happening in Firefox, it seems like the debug console is not telling the truth or there's something I'm not seeing. Here's the CSS for the body tag: html, body { width: 100%; } body { padding: 5% 10% 0 10%; ...

Incorporate SVG components into a unified repository shared user interface library without the need for webpack

Hey everyone, I've got a Yarn monorepo using Turborepo. Within this setup, I have 2 Next.js apps that both utilize some shared UI components: src |- apps/ (Next.js apps) |- packages/ui (UI library) I'm facing an issue where I can't incorpor ...

Troubleshooting: Nextjs application deployment on cPanel resulting in a 500 internal server error

Having migrated my website from React to NextJS for SEO purposes, I am now facing difficulties deploying it. Despite following a tutorial (https://www.youtube.com/watch?v=lex3qZAf_Ok&t=1136s) and consulting the official NextJS documentation (https://ne ...

Elevate your design game by mastering CSS transformations for precise element

I am trying to center a div with a variable width using the following code: div { background: red; max-width: 400px; position: absolute; left: 50%; transform: translateX(-50%); } Check out my demo here While this code works well for centering, ...

Aligning content within an <a> container

I am in the process of creating a square box that is clickable and will redirect users to another page. To achieve this functionality, as well as implement hover effects later on, I am utilizing the < a > element. Below is the HTML markup: <a id ...

Guide to integrating Material UI v5 with Next JS v12

A new version of Material UI, MUI 5, has been released. In the previous version (MUI 4), I used to connect it by making changes in _document.js and _app.js. Is the process the same for Material UI 5? for MUI v4 _app.js import CssBaseline from '@mat ...

Is there a way to utilize an Angular Material checkbox without any extra gaps or spacing?

Currently, I am working with Angular Material and trying to figure out how to remove the default spacing around the checkbox. The checkboxes in Angular Material are typically surrounded by some space (as shown in the image). Is there a simple way to elimin ...

What could be causing these "areas" or "panels" to intersect with each other?

As I work on constructing a website, I'm facing an issue with the top two sections. They appear correctly when my screen is full size, but as soon as I adjust the screen size, they jump down and create white space. It seems like I may have approached ...

I am having difficulty creating grid-template-columns in Vue

When I placed my code in the style scoped section... This is the desired output that I'm aiming for: .user-grid{ display: grid; grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); grid-gap: 1rem; } .user-car ...

Asynchronous functions within the next context

Hello there! I am trying to send the client's IP address from the frontend in a Next.js application to the backend. To retrieve the IP, I am using the following function: async function getIP() { var clientIP = await publicIp.v4(); ...

What is the process for clearing the cache of server actions?

Trying to figure out how to invalidate server action cache has been mind-boggling for me. In the Next.js documentation, there is a mention of `revalidatePath` and revalidateTag, but I am not able to see how they relate to the server-action. The server-ac ...

Fixed Container housing a Child Div with Scrollbar

I am faced with a challenge involving a lengthy navigation menu (.nav-main) nested within a fixed header (header). When the navigation menu is toggled using jQuery .toggle(), the content extends beyond the window height and does not scroll. I am looking fo ...

Render inline CSS styles with AngularJS

Can we use angular variables to write inline CSS styles? <div style="background: transparent url({{eventInfo.eventHeaderImg}}) top center no-repeat;"></div> Here is the output I received: "NetworkError: 404 Not Found - http://test/eventInfo. ...

Narrow down your search results with date range filtering in Angular Material

Seeking guidance as a newcomer to Angular Material, I am trying to implement a date range filter for a table of N results. The options in the filter select are (1 day, 5 days, 1 week, 15 days), which are populated using a variable JS vm.rangos=[ {id ...

Title size in css

<div class="products_list products_slider"> <ul> <li> <a id="ContentPlaceHolder1_rptCategoryProducts_hlProductImg_0" class="product_image" href="/Urun/Oyuncak/woodoy-100-parca-kovali-ahsap-oyuncak-bloklar/7078"> <div class="produ ...

The speed at which Laravel loads local CSS and JS resources is notably sluggish

Experiencing slow loading times for local resources in my Laravel project has been a major issue. The files are unusually small and the cdn is much faster in comparison. Is there a way to resolve this problem? https://i.stack.imgur.com/y5gWF.jpg ...