Issue with overlapping positioning of child components in React

I've come across multiple inquiries addressing this issue, yet none of them have provided a solution that fits my problem. In my scenario, there's a Parent component containing three Child components.

import React, { Component } from 'react'

import Header from "./Header";
import ChildOne from "./ChildOne"
import ChildTwo from "./ChildTwo"

class Parent extends Component {
  render() {
    return (
      <div>
        <Header />
        <ChildOne />
        <ChildTwo />
      </div>
    )
  }
}

export default Parent;

Each child element consists of a basic div. The components have been styled as follows:

.header {
  position: relative;
  width: 100%;
  height: 100px;
}

.childone {
  width: 100%;
  height: 480px;
  position: absolute;
  top: auto;
}

.childtwo {
  width: 100%;
  height: 240px;
  position: absolute;
  top: auto;
}

The desired outcome is for the React components to stack vertically, with the first child positioned at top: 100px; and the second one at top: 580px;

Given the need for responsive components, I require a flexible positioning approach.

However, the current issue is that ChildTwo ends up overlapping ChildOne.

Here, a potential solution is proposed, but I'm unsure how to implement it in my specific case. What would be the correct method to achieve the necessary positioning?

Answer №1

Avoid using absolute positioning and try a different approach.

Consider utilizing the flexbox CSS property instead: Find Complete Guide Here

Add a new class called flex to your main container div and define its properties in your CSS:

.flex {
  display: flex;
  flex-direction: column;
}

You can now eliminate the need for the top property on all child elements.

Remember that flexbox is responsive and offers more benefits compared to using absolute positioning;

Check out this Working Example

Answer №2

After examining your code, I managed to successfully stack all components one after the other by providing the specified top values.

The React components should ideally be displayed vertically, with the first child positioned at top: 100px and the second child positioned at top: 580px.

However, it seems that the CSS styles you posted have the "TOP" properties set to auto.

You can view my reproduction of the solution here: https://codesandbox.io/embed/sweet-dust-587oz

.header {
  display: block;
  position: relative;
  width: 100%;
  height: 100px;
}

.childone {
  display: block;
  width: 100%;
  height: 480px;
  position: absolute;
  top: auto; //I changed this to top: 100px;
}

.childtwo {
  display: block;
  width: 100%;
  height: 240px;
  position: absolute;
  top: auto; //I changed this to top: 580px;
}

Answer №3

There seems to be an issue related to CSS rather than React in this case. The current HTML output is structured like this:

<div>
  <div class="header">header</div>
  <div class="childone">child one</div>
  <div class="childtwo">child two</div>
</div>

It appears that Childone and Childtwo are not nested within the header as intended, but they are both children of the same parent div. Since they are absolutely positioned elements, they will align themselves based on the nearest parent that has relative positioning. Furthermore, both elements have the same top value (auto), causing them to overlap. To resolve this, adjust the top value of childtwo to 480px so it appears below childone. If you want both elements to appear after the header, set top: 100px for childone and top: 580px for childtwo (100px for the header's height + 480px for childone's height)

To visualize this better, consider adding a red border to your elements by including border: 1px solid red

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

Is the NPM Package Manager supported by default when I run the command "npx create-react-app my-app"?

"npx create-react-app my-app" When using this command, a react application is created with the NPM package manager by default. ALSO "npx create-react-app my-app --use-yarn" This command achieves the same result as the one mentioned ab ...

Storing user information in SQL database using React (entries to be defined)

I've been working on a website where I'm setting up a registration process. I have the registration form and server.js file using npm express, but I keep getting this error and can't figure out why. Error Message: TypeError: Cannot ...

How to dynamically render a component using useEffect in React.js/Next.js?

My goal is to develop a global message component for seamless integration into my Next.js pages. This component should be easily rendered with just one line of code, allowing me to use it throughout my entire application without the need to load it on each ...

"Troubleshooting: Why isn't my Tailwindcss box shadow

I'm currently incorporating Tailwindcss into a React project to recreate the Star Wars website mobile menu. However, I am facing an issue where the box shadow added to the hamburger icon segments is not visible when the navigation drawer is opened. A ...

Issues with WordPress's multiple menu functionality not functioning as expected

I've been working on setting up multiple menus in WordPress, and I've run into a little issue. I managed to create the menus, assign them to their respective locations, and save them successfully. However, when I try to call the footer menu, it e ...

Pagination with React Material UI is a user-friendly and visually

Requirement Within the Material UI framework, I need to implement pagination functionality by clicking on the page numbers (e.g., 1, 2) to make an API call with a limit of 10 and an offset incrementing from 10 after the initial call. https://i.stack.imgur. ...

When deploying a Node.js Express API using Docker, the headers are not being sent

After creating a Node.js Express API, I implemented the /login endpoint for users to authenticate and receive an Authorization Token: @Post('/login') @UseBefore(validationMiddleware(LoginUserDto, 'body')) async logIn(@Res() res: R ...

Having trouble getting PostCSS nesting to work with CSS variables in Tailwind CSS and Next.js?

I've been attempting to utilize PostCSS nesting alongside CSS variables, but unfortunately the CSS variables are not being converted at all. Instead, I am seeing Invalid property value in the DOM for CSS Variables. The tailwind.css file I have inclu ...

The aesthetic of react-bootstrap and material ui aesthetics is distinctive and visually appealing

As I develop my web application, I have incorporated react-bootstrap for its React components based on Bootstrap. However, wanting to give my project a customized look inspired by Material design, I came across bootstrap-material-design. I am curious if I ...

Utilizing React Native for Seamless Navigation: Understanding Stack and Tab Navigation (Ensuring the route component is a React component)

Attempting to create a StackNavigator that can navigate into a TabNavigator, but encountering an error stating: "The component for route must be a React component." The TabNav is not a physical file folder; it is intended to be called once the user logs i ...

Revise a function that locates an object with a corresponding id in an array, modifies a property, and updates a React component's state

Here is a function that takes in a rating value within an object. The ID and Question properties remain unchanged, but the rating value can be updated. This will result in updating a React state value. Is there a method to improve the readability and con ...

Firefoxi is the only browser that exhibits strange padding and margin behavior

Check out this webpage at: www.bit.ly/1b4dUqs Most browsers display the page correctly, but there seems to be an issue with Firefox's (latest version) handling of margin-top/padding-top styles. If anyone has a solution for this problem, please share ...

What are the steps for utilizing next-connect with a host proxy while working on development tasks?

My backend API server is restinio, and in the past, I used ReactJS for the front-end. To address a proxying issue, I added "proxy": "http://localhost:4000" to my package.json file as explained in this documentation: https://create-react ...

Guide to indicating the chosen filter in React using Material UI

I'm currently working on a blog that includes a filter feature. The filtering functionality is working perfectly, but I am trying to specify which filter option is currently selected. Here is the code snippet: {cardCategories.map((cat) => { retu ...

Guide to setting up a new create-react-app project after removing an existing one

(base) Dun-Yan:Web development.HTML ongdunyan$ sudo npm uninstall -g create-react-app Password: up to date, audited 1 package in 429ms found 0 vulnerabilities (base) Dun-Yan:Web development.HTML ongdunyan$ sudo npm install -global <a href="/cdn-cgi/l/ ...

Issue with the Z-Index property not functioning as expected on unordered lists within a dropdown menu

I have a dropdown menu that opens to the left, but it is displaying underneath the content. I attempted adjusting the z-index of the content to 1 and the dropdown to 2, however, this did not resolve the issue. Here is a sample in jsFiddle: https://jsfiddl ...

What is the best way to ensure a textarea remains expanded when the parent element is in focus?

I have successfully implemented a textarea box that expands upon click and retracts when it loses focus. However, I am facing an issue where if the textbox is already in expanded form, I want it to stay expanded if the user clicks anywhere within the cont ...

Is it worth exploring if using useCallback will truly boost performance or be advantageous in any way?

I understand the purpose of useCallback and that it can be useful for maintaining reference equality. However, in my specific case, it would primarily serve as a potential performance optimization. Since this is for a React Native project intended to run o ...

Ensure that both the div element and its contents are restricted to a maximum width of

I'm having trouble arranging the display of information next to a plant image. I want to ensure that the information stays on the right side of the image when the screen reaches a specific minimum width. The issue arises when the information includes ...

Is the presence of hidden list items leading to excessive white space?

I have a menu that appears when hovering over a list item. Here is an example: <li> <ul class="topmenu"> <li class="submenu"> <a class="otherIT" href="#" title="Common IT Tasks"><img src="./images/ittasks.png" alt= ...