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

"How can you enhance the performance of JavaScript and CSS in a Chrome Extension without using exclude_matches/globs or excluding domains

I have been in the process of creating a Chrome Extension, and unfortunately, when I tried to make it work on specific URLs, I encountered an issue. While Chrome has options like exclude_matches and exclude_globs for this purpose, there seems to be a bug i ...

Guide on incorporating a refresh button to automatically update information from a database in MaterialUI's Datagrid

Recently diving into JavaScript, I encountered a common issue: The data for my table is sourced from a MySQL database through Axios Whenever CRUD operations are performed in the web app, the database is updated accordingly Although backend changes ...

MUI: The default value state of an uncontrolled Rating is being modified by a component after its initialization

Can you identify the issue causing this error: MUI: A component is altering the default state value of an uncontrolled Rating after initialization. To avoid this warning, consider using a controlled Rating instead. const StarsRating = (props) => { ...

Is it possible to adjust CSS values in a relative manner?

#bar{font-size:14px;} The font size of #bar is set to 14px. #foobar{font-size:$-2px} // Fictional code The font size of #foobar is now 12px. (calculated as 14px - 2px) Is there a way to dynamically alter the value of a selector like this? ...

When TypeScript tsc is unresponsive, there is no output or feedback provided

Just getting started with TypeScript! I've been working on transitioning my React.js project from JavaScript to TypeScript. I managed to resolve all the bugs and verified that it runs smoothly when using npm start. However, whenever I try to comp ...

An issue arises in Slate.js when attempting to insert a new node within a specified region, triggering an error

A relevant code snippet: <Slate editor={editor} value={value} onChange={value => { setValue(value); const { selection } = editor; // if nothing is currently selected under the cursor if (select ...

Background not covering full height despite setting HTML and body heights to 100%

I've been struggling to set my wrapper to 100% height, despite setting the height to 100%. Any solutions? At the moment, my main_wrapper is empty and should have a background color of red. While I'm looking to add a footer using position: fixed ...

Error: The function eleves.map is not supported in React/Spring-boot, causing a failure to display the @ManyToOne relation

Currently, I am encountering an issue with displaying 2 entities in a Many to One relationship. When the data is saved in the student entity with the level entity left as null, everything works smoothly because the response is an object. However, when a s ...

How can a server component be rendered conditionally based on the state set in the client component?

Currently, I am working on implementing a tailwinds css template sidebar that updates the main div with components based on the active sidebar tab. To achieve this functionality, I need to utilize state to determine which sidebar tab is currently active. I ...

Specify padding or margin for all sides in a single line of XML code

Is there a way to set the padding or margin for all four sides in xml with just one line, similar to how we can do it in css? For instance, in css: padding: 1px 2px 3px 4px; Is there an equivalent method in xml for accomplishing this? ...

Unable to set value using React Hook Form for Material-UI Autocomplete is not functioning

Currently, I am in the process of constructing a form using React-Hook-Form paired with Material-UI. To ensure seamless integration, each Material-UI form component is encapsulated within a react-hook-form Controller component. One interesting feature I a ...

Simple Method To Dynamically Align jQuery LightGallery Thumbnails On a Responsive CSS Website

Can anyone assist me quickly? I've implemented everything but am facing a slight issue with the centering of my ul code. I've tried various solutions without success. Here is my code, any advice would be greatly appreciated (I may sound stressed ...

Unfold an HTML element and reveal a sneak peek of its content with the aid of JQuery

I need a way to organize and display a set of 5 lines of text vertically. Specifically, I want them arranged like this: 1) Line one 2) Line two 3) Line three 4) Line four 5) Line five However, I have a special requirement where only the first ...

Material-UI is having trouble resolving the module '@material-ui/core/styles/createMuiTheme'

Although I have searched for similar issues on StackOverflow, none of the solutions seem to work for me. The errors I am encountering are unique and so are the fixes required, hence I decided to create a new post. The company conducting my test provided m ...

What is the reason behind text underline being disabled when using "hidden: overflow" in CSS?

I have a long text string that I want to auto-shorten using CSS with text-overflow: ellipsis, but it's removing the underline from my link. Here is the code: NORMAL .link { font-weight: bold; cursor: pointer; color: black; text-decorat ...

React Native Modal Problems

Hello everyone, I am a newcomer to this new technology and I am encountering a slight issue with modals. I am working on a modal that should only appear when a certain condition is met. The first click works fine, but on the second click, the modal fails ...

Why isn't my React cascading select filter working properly on onChange event?

I'm new to React and facing an issue in my app. I have a set of options fields in my drawer on the left side, where each subsequent option depends on the selection of the previous one. The problem arises when my filter function returns an empty array ...

The `Home` object does not have the property `age` in React/TypeScript

Hey there, I'm new to React and TypeScript. Currently, I'm working on creating a React component using the SPFX framework. Interestingly, I'm encountering an error with this.age, but when I use props.age everything seems to work fine. A Typ ...

Tips for updating a URL using data obtained from a JSON response

As I loop through an array from JSON, I extract all the necessary information. For example, if I have cards for blog posts that include the title, short description, published date, and URL. When clicking on a card, it redirects to a corresponding page ba ...

Transform a traditional class component into a functional component

Is there a way to successfully convert this class component into a function component despite my previous failed attempts? componentDidMount(){ const id = this.props.match.params.id; getById( parseInt(id) ) .then(product => { this.setS ...