What is the best way to display a child div without impacting the position of other elements within the same parent container?

As I work with a div html tag within a login form, encountering an error inside this form has presented a challenging issue. The error div sits at the top of its parent div, and ideally, upon activation, should remain within the form div without disrupting its position or size. Implementing position: absolute in the child div only resulted in it remaining fixed at the left corner of the parent div. Using z-index did not prevent the parent div from shifting by the height of the child div. The following code snippet illustrates this scenario:

<div id='formulario' style={{height: 400px}}>
    {this.props.auth.error && <div id='erro' style={{height:'15px'}}>Nao foi possivel fazer o login!</div>}
    <div id='login'>
    ...
   </div>
</div>

Upon validation of this.props.auth.error, the error message displays causing the form to expand to 415px. How can I ensure that the #formulatrio div stays at a size of 400px while keeping the #login div intact when the error is triggered?

Answer №1

adjust the top CSS attribute to reposition the login div, included a background for better visualization.

class MaintainPosition extends React.Component {
  render() {
    return (
      <div
        id="form"
        style={{ height: "400px", backgroundColor: "lightblue" }}
      >
        {this.props.auth.error && (
          <div id="error-msg" style={{ height: "15px", color: "red" }}>
            Unable to login!
          </div>
        )}
        <div id="login">
            scroll down to show error message
        </div>
      </div>
    );
  }
}

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      error: true
    };
  }
  render() {
    return (
      <div className="App">
        <MaintainPosition auth={{ error: this.state.error }} />
        <button onClick={() => this.setState({ error: !this.state.error })}>
          toggle error
        </button>
      </div>
    );
  }
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
#err {
  
}

#form {
  position: relative;
}

#login {
  position: absolute;
  width: 100%;
  top: 20px;
  background-color: gray;
}

#root {text-align: center}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>


<div id="root"></div>

Answer №2

Just wanted to give this a go by incorporating the background.

<style>
    #formulario {
        display: grid;
        align-content: center;
        width: 400px;
        height: 400px;
        background: grey;
    }
    #erro {
        position: relative;
        width: 100%;
        height: 15px;
        background: yellow;
        text-align: center;
    }
</style>

<div id='formulario'>
    {this.props.auth.error && <div id='erro'>Unable to log in!</div>}
    <div id='login'>
        ...
    </div>
</div>

Answer №3

Is this what you had in mind?

The important thing to remember is to designate the parent element as relative so that the child elements know how to position themselves.

$('button').on('click', function() {
  $('#error-message').toggle();
});
#form-container {
  border: 1px solid #DDD;
  position: relative;
}

#error-message {
  background-color: rgba(255,0,0,.5);
  text-align: center;
  position: absolute;
  width: 100%;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<button>Show/Hide Error Message</button>

<hr>

<div id='form-container' style='height: 400px'>
    <div id='error-message' style='height: 15px'>Login failed!</div>
    <div id='login-info'>
      Username<br/>
      Password<br/>
      Login Button<br/>
   </div>
</div>

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 Jquery to add new HTML content and assign an ID to a variable

Here is some javascript code that I am having trouble with: var newAmount = parseInt(amount) var price = data[0]['Product']['pris']; var id = data[0]['Product']['id']; var dat ...

It appears that Promise.all is not adequately ensuring that all tasks are completed before moving on

In my current project, I am trying to achieve a complex cycle where an HTTP GET request is executed to fetch data, followed by the creation of multiple "subrequests" based on that data. The goal is to ensure that the next iteration of the cycle begins only ...

Understanding how to effectively conduct unit tests on the 'resolve' property within an Angular-UI Bootstrap Modal component is essential for ensuring the functionality and

I'm currently working on building a unit test that verifies the correct variable is being passed to the resolve property within the ui.bootstrap.modal from Angular-UI Bootstrap components. Here's my progress so far: // Controller angular.module( ...

Aligning a table at the center of another table

Frustration has been brewing within me all week as I grapple with the task of sending out an important emailer soon. The challenge lies in aligning these product images next to their descriptions at the center, a feat that seems impossible to achieve withi ...

Manipulate the contents of children divs within a parent div using JavaScript or JQuery

<div id="abc"> <div id="a_b"> abcd </div> <div id="c_d"> xyz </div> </div> I have a challenge where the divs on my page are generated dynamically and their IDs change every time the page loads. When the window i ...

Updating the DOM after scrolling using jQuery

jQuery hover functionality is not working correctly after scrolling. $(document).ready(function() { $('img').hover(function(){ alert('hello'); },function(){ alert('hello not'); }); }); When hoveri ...

Issue with flexbox max-width property not being applied when resizing the page width

I'm struggling to make a flex box with max and min width properties work properly. When I reduce the page size, it ends up showing blank space instead of resizing. How can I troubleshoot this issue? .parent{ border: 1px solid red; width: 50%; ...

When you use the useState object in NextJS, the context object may appear to be empty

I've encountered an issue while trying to pass a context object in NextJS that uses data from a useState hook. Strangely, the state variable and setState functions are undefined when consumed. It's puzzling because substituting a simple variable ...

Using data from an API, I am implementing JavaScript validation for my dropdown select menu

Using an API, I am able to access information about the city's subway stations through a select option. Currently, I can only display details about one station (Balard). However, I would like to be able to display information about other stations tha ...

Hidden overflow and identification in URL causes content to be invisible and suddenly appear at the top of the page

I'm encountering a strange issue with containers that have overflow:hidden and when the page URL includes an id. The content gets pushed up and becomes invisible. This problem arises when I apply padding and negative margin at the bottom to create equ ...

What is the best way to group a Pie Chart by a string field in a .csv file using dc.js, d3.js, and crossfilter.js in a Node environment?

I've successfully set up several Dimensions and groups, but I'm encountering an issue with a Pie Chart that needs to be grouped based on domain names like bing.com. Each domain name is parsed consistently to xxxx.xxx format and the data is clean. ...

Troubleshooting Java REST service integration in AngularJS for UPDATE and DELETE operations

After successfully implementing a REST service with Java and testing all HTTP methods using Postman, I decided to explore AngularJS. Upon integrating it to consume the REST service, I encountered issues specifically with the Delete and Put methods not func ...

When data is stored in Internet Explorer's cache, any changes made are not being reflected in

Internet Explorer stores data in cache and even if there are changes, it may not reflect onclick. However, when I open the developer mode and try to access the same, then it works perfectly. This issue only seems to occur in IE as all other browsers work f ...

The timing of the JavaScript dialog with the AJAX call is off-kilter

Encountering an issue with a JavaScript script designed to showcase a JQUERY dialog box based on a C# ViewModel. Within a repeater, there is an ASP drop-down menu displaying 'Registration Date' details. The objective is for the JavaScript dialog ...

Can the Angular.js scope be maintained while also making changes to the template?

I am currently facing a challenge with my directive. In the snippet below, I am attempting to extract content from a template, append it to the layout, and then compile it: var $template = angular.element("<div></div>"); $template.append($co ...

Building a Multifaceted Website using React and Node.js

I've encountered a rather straightforward issue. My goal is to incorporate a second checkout page into my React and Node Website. I initially believed that the solution would be as simple as adding another 'checkout' Route to the Browser Ro ...

Error encountered in node.js script due to misuse of Sqlite's SQLITE_MISUSE functionality

Upon running my code with this query, I have encountered a situation where all tables are listed sometimes, while other times only one table is shown and consistently the following error is displayed: Query Error: Error: SQLITE_MISUSE: unknown error I ha ...

What is the best way to load the route calculation dynamically?

I am struggling with calculating the Google Maps route dynamically. The console shows an error stating that 'calcularRuta' is not defined: Uncaught ReferenceError: calcularRuta is not defined at HTMLInputElement.onclick (index.html:1) Despi ...

Dynamically Alter Notification Background

I have created a demo page with some code for a smart notification. The issue I am facing is that even though the CSS is initially set to black, I want to dynamically change it to a random color upon creation. When I try to do this in the inspector, it w ...

Show just three items simultaneously

I am currently working on a quote generator and I want to add a feature that allows me to display a specific number of quotes at a time. I attempted to use map for this purpose, but encountered an error stating it's not a function. Currently, the gene ...