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

Examining website design on an IOS device from a Windows computer

Is there a way for me to test HTML files from Windows on iOS8 (Local Files)? I have tried Adobe Edge Inspect, but it only works with servers. Are there any free cloud hosts that allow for HTML, CSS, and JS files? Edit: I apologize if my question was not c ...

Creating a clickable color-changing grid: A step-by-step guide

In a grid of size 12 by 12, each corner will be clickable, selecting a 6x3 cell area starting from the corner. The selected cells will change color upon clicking any of the 4 corners. After selecting one corner, the remaining cells (126 cells) will be che ...

Iterating through an array of MongoDB document IDs, querying each ID and then storing the results in a new array results in an empty array

Having trouble with the following code: const users = [] event.registeredUsers.forEach(userId => { User.findOne({ _id: userId }).then(user => { console.log(user) // displays a valid user users.push ...

Execute AngularJS code when a button is clickeddoubleValue

I am in the process of developing a dynamic page where users can add anywhere from 1 to n products effortlessly. Although I have been exploring AngularJS for several months, I find myself facing some challenges when conceptualizing this scenario. The HTM ...

tips for dynamically highlighting search bar after choosing a different dropdown option - vuejs

I need to filter products in my application based on name and category. To achieve this, I have included a search text box and a dropdown select box. The dropdown select box offers two options: 1. Search products by name 2. Search products by category name ...

In order to utilize the componentDidUpdate lifecycle method, I passed props to the Outlet component while nesting it

I am currently using react-router-v6 and encountering some issues with my configuration. I have implemented nested routing with layouts according to the following settings. App.js <BrowserRouter> <Routes> <Route exact pat ...

Maintain the tab order for elements even when they are hidden

Check out this demonstration: http://jsfiddle.net/gLq2b/ <input value="0" /> <input id="test" value="1" /> <input value="2" /> By pressing the TAB key, it will cycle through the inputs in order. If an input is hidden when focused, press ...

Is there a way for me to modify the position of a cursor graphic?

Similar Question: Custom cursor interaction point - CSS / JQuery I've been experimenting with changing the image of the mouse pointer by using the CSS cursor property ("cursor: url(images/target.png), crosshair;") and have observed that when a us ...

The navigation bar in responsive view on Bootstrap 4 causes the content below it to shift

Recently I have been exploring bootstrap-4 and encountered an issue while creating a nav-bar. The problem is that in responsive view, when toggling the nav-bar it simply pushes the content below it. Is there any way to address this issue within (bootstra ...

Methods for validating ajax response with Jasmine

I'm a newbie when it comes to jasmine and I'm trying to figure out how to verify if a specific node is present in the ajax response. Currently, I'm using grunt to run jasmine from the command line and have successfully tested if a function i ...

PHP code exhibiting inconsistent behavior when executed on a WAMP Server

My WAMP Server is set up and running smoothly as I dive into PHP code for a class assignment. The server icon shines bright green, my HTML and PHP files in the www folder are functioning perfectly. I am currently using PHP v7.0.1 on my WAMP setup. However ...

The GitHub-hosted package encounters a failure during the npm publish process

Last week everything was running smoothly, but now I am encountering an error and not sure what went wrong. (Apologies for the formatting as there are many lines of log) Running Node version: v10.15.3 Using npm version: 6.4.1 After executing npm publish ...

When toggling visibility with JS, the Bootstrap Grid Row may not center-align as expected

Sorry for the odd spacing issue that might occur. I currently have a basic Bootstrap Grid setup as follows: <div class="row justify-content-center" align="center" id="details"> <div class="col-sm-2"> ...

Update the website's navigation key for improved user experience

Can the navigation key on a website be altered from 'Tab' to another key, such as 'Enter', allowing for the focus to shift to the next element with the corresponding 'tabindex' when the 'Enter' key is pressed? ...

Preventing Page Scroll While New Data is Loading

I am currently working on a React class component that uses Post components. Within this component, there is a button that triggers the loading of more data from the database. The issue I am encountering is that when new data is fetched, the page automatic ...

Paused session in web development

Currently, I am in the process of building a website using HTML and CSS and have encountered an issue. Within my CSS file, I have defined an ID called "full" which sets a wooden background after the sidebar and is intended to span across the entire page. A ...

What is the best way to refresh a Windows 7 command prompt screen before executing a new function in Node.js?

I attempted system calls for cls and also tested out this code snippet: function clear() { process.stdout.write('\u001B[2J\u001B[0;0f'); } Unfortunately, none of the options seem to be effective. ...

Exploring the efficiency of AngularJS when binding to deeply nested object properties

Are there any performance differences to consider when data binding in Angularjs between the following: <div>{{bar}}</div> and <div>{{foo.bar}}</div>? What about <div>{{foo.bar.baz.qux}}</div>? Our team is working o ...

What is the best way to include a hyperlink in the same line?

I was curious about how to insert a hyperlink following some text: If you need more information on PCSE, make sure to check out the FAQ section on the PCSE website. (INSERT LINK HERE) <div class="panel-body"> <p>If you require any further inf ...

Activate the places_changed event in Google Maps by clicking the submit button

I would like to activate my placed_changed function when a submit button is clicked. Here's what I have so far: I've set up a searchbox using google.maps.places.SearchBox, and when I press enter while the search box is in focus, it triggers the e ...