The phenomenon of an invisible Absolute or relative position leading to grid components overlapping in Next.js

I've been struggling with this issue for over 48 hours now. I've attempted to troubleshoot by commenting out everything except the affected components and even swapping entire components around, but the problem persists. Oddly enough, rearranging their positions resolves the overlapping problem temporarily, but as soon as I revert back to the original layout, the elements overlap again. Any assistance would be greatly appreciated!

This code is from the pages/post/[slug].js page
import Head from "next/head";
import { useState } from "react";
import styles from "@/styles/product.module.scss";
import db from "@/utils/db";
import Header from "@/components/header";
import News from "@/models/News";
import MiniNews from "@/components/home/mini";
import Category from "@/models/Category";
import MainPost from "@/components/productPage/mainPost";
import ForCategories from "../../components/breakingNews/ForCategories";
import ForCreators from "@/components/breakingNews/ForCreators";
export default function product({ post, related, news, categories }) {
  const [activeImg, setActiveImg] = useState("");
  console.log(post);

  const country = {
    name: "Nigeria",
    flag: "https://cdn.ipregistry.co/flags/emojitwo/ng.svg",
  };
  return (
    <>
      <Header country={country} />
      <div className={styles.product}>
        <div className={styles.product__container}>
          <div className={styles.path}>
            Home / {post.category.name} / {post.name}
          </div>
          <MiniNews news={news} />
          <div className={styles.product__main}>
            <div className={styles.product__main_one}>
              <MainPost post={post} />
            </div>
            <div className={styles.product__main_two}>
              <ForCategories
                categories={categories}
                header="All Categories"
                bg="#379237"
              />
              <ForCreators news={news} header="All Categories" bg="#379237" />
            </div>
          </div>
        </div>
      </div>
    </>
  );
}

export async function getServerSideProps(context) {
  try {
    const { params } = context;
    const slug = params.slug;
    await db.connectDb();

    // fetching post data based on slug
    let post = await News.findOne({ slug })
      .populate({ path: "category", model: Category })
      .lean();
    if (!post) {
      return {
        notFound: true, // Return 404 page if post is not found
      };
    }

    // fetching all post data
    let news = await News.find()
      .populate({ path: "category", model: Category })
      .sort({ createdAt: -1 })
      .lean();

    // fetching all category data
    let categories = await Category.find().sort({ createdAt: -1 }).lean();

    return {
      props: {
        post: JSON.parse(JSON.stringify(post)),
        news: JSON.parse(JSON.stringify(news)),
        categories: JSON.parse(JSON.stringify(categories)),
      },
    };
  } catch (error) {
    console.error("Error fetching post:", error);
    return {
      props: {
        post: null,
        news: null,
        categories: null,
      },
    };
  }
}

Here is the styling for the slug page:

.product {
  height: 100%;
  background: #eeeeee;

  &__container {
    padding-top: 1rem;
  }
  .path {
    max-width: 95%;
    margin: 0 auto;
    font-size: 10px;
    color: #1e1e1e;
  }
  &__main {
    padding: 20px 15px;
    max-width: 95%;
    margin: 0 auto;
    position: relative;
    margin-top: 1rem;
    gap: 1rem;
    background: #fff;
    display: grid;
    grid-template-columns: repeat(12, 1fr);
    gap: 2rem;
    &_one {
      grid-column: span 9;
      height: 100%;
    }

    &_two {
      grid-column: span 3;
    }
  }
  @media (max-width: 900px) {
    &__main {
      grid-template-columns: repeat(1, 1fr);
      padding: 0 5px;
      gap: 0;
    }
  }
}

The div elements with the style.product__main class behave correctly on larger screens. However, when the screen size is reduced below 900px, instead of displaying as a neat column, the element with the style.product__main_two class appears above the style.product__main_one element in an odd manner. I have exhausted all my ideas for fixing this and even changed the content of div two to just a paragraph, but the issue remains. There are no absolute positioning properties at play here aside from the relative positioning indicated in the main styling, which also does not solve the problem when removed. Your help would be greatly appreciated.

Answer №1

Upon investigating, I discovered that the issue originated from the styling within a specific component.

import styles from "./styles.module.scss";
import ReactImageMagnify from "react-image-magnify";
import { useState } from "react";
import { MdOutlineLibraryBooks } from "react-icons/md";
import { IoTimeOutline } from "react-icons/io5";
import dayjs from "dayjs";
import { LiaCommentSolid } from "react-icons/lia";
import { HiShare } from "react-icons/hi";

export default function MainPost({ post }) {
  const [active, setActive] = useState(0);
  return (
    <div className={styles.mainpost}>
      <div className={styles.mainpost__list}>
        <p className={styles.mainpost__list_category}>{post.category.name}</p>
        <h3 className={styles.mainpost__list_name}>{post.name}</h3>
        <div className={styles.mainpost__list_timestamp}>
          <span className="flex">
            <IoTimeOutline /> {dayjs(post.createdAt).format("MMMM D")}
          </span>
          <span className="flex">
            <MdOutlineLibraryBooks /> 2 mins Read
          </span>
        </div>
        <img src={post.image} alt="postImage" />
        <div className="flex items-start gap-4">
          <div className={styles.textOverlay__timestamp}>
            <span className="flex flex-col items-center justify-center">
              <LiaCommentSolid />{" "}
              <p className="text-[0.5rem] text-center">Add Comment</p>
            </span>
            <span className="flex flex-col items-center justify-center mt-[1rem]">
              <HiShare />{" "}
              <p className="text-[0.5rem] text-center">Share Post</p>
            </span>
          </div>
          <p dangerouslySetInnerHTML={{ __html: post.post }}></p>
        </div>
      </div>
    </div>
  );
}

Styling adjustments were made to:

.mainpost {
  &__list {
    margin-top: 7px;
    display: flex;
    flex-direction: column;
    gap: 2px;
    height: 130px;
  }
}

The issue of overlapping elements was resolved by changing the height setting from 130px to 100%. height: 100%;

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

Using JavaScript, verify if the user is connected to a network

Does anyone know of a simple method to verify if the user is able to access our website? Determine if they are not receiving a connection error. ...

Utilizing Paragraph Styles Within a CSS Stylesheet

I'm attempting to create two unique styles for a pair of paragraphs in an xhtml document by utilizing a CSS style sheet. Despite my efforts and extensive search, I have yet to find a clear solution. ...

jQuery selector unable to locate the specified class in the table row

After receiving an array of strings as a response from an SQL query, I am using JavaScript to dynamically add this data as rows to an HTML table: loadUsers: function() { . . . function displayUsersOnTable(response) { for(var i = ...

The settings of the button return to their default state once it is clicked on

I've been working on a small project and I added a button with hover and CSS effects. However, the issue is that once the button is clicked, it reverts back to its basic state without any of the CSS properties applied. I attempted to troubleshoot if ...

When using jQuery's `.click()` method on an element to collapse it with the 'show' parameter set to false, the disabling action will only take effect after the document

When you first run the program and click anywhere on the body, it activates the collapse element. I want it to only collapse the accordion on click, not show it immediately. Currently, it will deactivate only after it is hidden once. HTML <!DOCTYPE ht ...

Implementing a clickable search icon within a form input field using CSS: a guide

I have added a search icon to the form input field. Check it out here: https://i.sstatic.net/pnv6k.jpg #searchform { position: relative; } #searchform:before { content: "\f118"; font-family: "pharma"; right: 0px; position: absolute; ...

Counting the total number of lines within a div element

Can someone help me figure out how to accurately determine the number of lines in a div? I tried using this example on jsfiddle, but it's giving me 9 instead of 5. Any suggestions on what might be causing this discrepancy? var lines = document.getEle ...

Fixing the Access Denied Issue in Next.js 13.4 with the Help of NextAuth Google Login and MongoDB

Currently, I am working on integrating Google login with Next Auth in Next.js version 13.4. My issue arises when I attempt to log in using Google; it redirects me to the following Google page link: "http://localhost:3000/api/auth/signin?callbackUrl=http%3A ...

Ajax is unintentionally duplicating the request

When the "async" parameter is set to "true", ajax sends two requests at the same time. But, when it is set to "false", there are no issues. To prevent the page from reloading, I am using the following code: $(document).ready(function() { $(document).on(& ...

Tips for creating uniform image sizes within the Next Image component

Check out my NextJS app on CodeSandbox here. In this project, I am using Tailwind CSS for styling and rendering a list of products. Each product is displayed in a card with an image. I am utilizing the NextJS Image component for image rendering, but I am f ...

Aligning the canvas resolution to match the video resolution for superimposition purposes

Within a div, I have both a canvas and a video element: <div id="videos"> <canvas id="my-canvas"></canvas> <video id="remote-video" autoplay></video> </div> Below is the css styling for both elements: #my-canv ...

Creating a clickable navigation menu item with a clickable caret located on the same line

I've been developing a solution using Twitter Bootstrap to create a main navigation menu that expands upon hover on desktop, while the menu expands when clicking the caret on mobile (caret hidden on desktop). Additionally, I aimed to make the top-leve ...

After triggering an action, I am eager to make a selection from the store

To accomplish my task, I must first select from the store and verify if there is no data available. If no data is found, I need to dispatch an action and then re-select from the store once again. Here is the code snippet that I am currently using: t ...

How come an absolutely positioned element does not disregard its sibling's position and appears after it?

<div> is styled flexibly, while <section> is inserted within it and formatted statically. However, <section> shows up underneath the lower right corner of the image, rather than at the upper left corner of its flexible parent. I am strugg ...

The terser-webpack-plugin and uglifyjs-webpack-plugin are both powerful tools for optimizing

WebPack 4 now utilizes the terser-webpack-plugin in production mode or when the -p argument is specified, which essentially means including --optimize-minimize --define process.env.NODE_ENV="production". This plugin is responsible for minimizing ...

Retrieve the property value from a nested object using a key that contains spaces

Presenting my object: let obj = { innerObj: { "Key with spaces": "Value you seek" } } Upon receiving, I am unaware of the content within obj. I possess a string variable holding the key to access the value. It appears as follows: let ke ...

Angular's ngRoute is causing a redirect to a malformed URL

Currently, I am in the process of developing a single-page application using AngularJS along with NodeJS and Express to serve as both the API and web server. While testing locally, everything was working perfectly fine. However, after cloning the repositor ...

Using Jquery to send json data to a webserver via Ajax (API)

Currently, I am attempting to use AJAX to post data to a JSON file (API) on a server. As part of this process, I have implemented dragging functionality for two Kineticjs shapes on the stage. Upon stopping the drag action, my goal is to save the updated x ...

Decipher intricate JSON with JavaScript

After retrieving a JSON object from Mongo DB, I have this data structure. **JSON** { "_id" : ObjectId("5265347d144bed4968a9629c"), "name" : "ttt", "features" : { "t" : { "visual_feature" : "t", "type_feature" : ...

Using AngularJS: The ultimate guide to invoking a service within a module

I have a controller that successfully calls a service. However, I now need to access a method within that service from another module. How can I achieve this? BaSiderbarService: (function() { 'use strict'; angular.module('BlurAdmi ...