Achieve horizontal centering of modal without the use of jQuery

Currently, I am developing a modal within a React application. The modal's width is set to auto and its position is set to fixed. My goal is to center it horizontally in the middle of the screen.

.Modal {
    position: fixed; 
    width: auto;
    z-index: 500;
    align-content: center;
    background-color: rgba(255, 255, 255, 0.889);
    border: 1px solid #ccc;
    box-shadow: 5px 5px 5px black;
    padding: 0px;
    font-size: 12px;
    box-sizing: border-box;
    transition: all 0.3s ease-out;
}

I have experimented with several solutions found on Stack Overflow to achieve the centering of the modal.

The primary issue I am encountering is that the modal appears above other elements due to its z-index property. When attempting to change the position to absolute as recommended in most solutions, the items rendered below it on the z-index appear shifted down on the screen. This approach does not suit my requirements.

Answer №1

To center your content, consider including margin:0 auto; in your CSS and eliminating the fixed positioning.

Answer №2

If you try to apply "margin: 0 auto;" to an element that has a fixed position, it won't work as expected.

You have two options: remove the fixed position and use margin: 0 auto;

Or Calculate the left position as (50% - width of the element / 2).

But the simpler solution would be to go with the first option.

Answer №3

When using a fixed position for your modal, adjusting the horizontal position can be done by using the left or right CSS properties. However, having a 'width' set to auto may not be effective as the width can vary. One solution is to wrap the modal in a parent div, as shown below:

.modal-parent {
  position: fixed; 
  display: flex;
  justify-content: center; 
  align-items: center; 
  top: 0;  
  left: 0;  
  width: 100%; 
  height: 100%; 
  background: rgba(0, 0, 0, 0.5);
}

.modal {
  padding: 40px; 
  background: white; 
}
<div class='modal-parent'>
  <div class='modal'>

  </div>
</div>

Alternatively, if you prefer not to use a parent div, you can set a static width for the modal, allowing the height to vary:

.modal {
  position: fixed; 
  padding: 40px; 
  box-sizing: border-box;
  top: 0;  
  left: calc(50% - 150px);  
  width: 300px;
  background: teal;
}
<div class='modal'>

</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

When attempting to declare a functional component in React utilizing styled-components in TypeScript, an error is encountered stating "No overload matches this call."

Playground https://codesandbox.io/s/typescript-type-checking-question-0b42t Sample Code type BadgeTypes = { success: string; secondary: string; alert: string; text: string; }; type Theme = { fonts?: object; borderRadius: string; primary?: o ...

Generate interactive jQuery slideToggle containers that monitor user clicks via Google Analytics

I have been working on a PHP and mySql project where I need to retrieve a list of businesses from a database. Once I have the desired businesses, I want to display them consecutively inside their own "clickDiv" container using jQuery slideToggle to reveal ...

Extract the content within the span tags while preserving any line breaks

I have a situation where a span element contains text with line breaks, and there is a function in place to copy this content to the clipboard. My goal is to maintain the line breaks when the data is pasted into another tool or page that supports HTML. C ...

I'm working with Angular 12, Bootstrap 5, and ngPrime, and I'm looking to overlap a p-dialog with another element in my project

Is there a way in Angular 12 with Bootstrap 5 using ngPrime to overlap a p-dialog over any other element without using z-index and CSS, solely relying on PrimeNG? I have tried using z-index with: .my-class{ z-index: 2147483647 !important; } However, ...

What steps should I take to resolve the issue when axios in React returns the error message "Unhandled Rejection (error): Network error"?

I've been developing a React Application that's running on localhost:3000. I'm attempting to fetch data from a .NET Core Application hosted at localhost:5001 using the axios library for making HTTP requests. Here's the function I' ...

What is the best way to insert HTML elements in front of other HTML elements using a form and jQuery?

I am looking to insert new HTML elements before existing ones using a form and jQuery: Here is the initial HTML Code: <div class="main-content"> <h2 class="main-content-header">Projekte</h2> <div class="project-content"> ...

Do I really need to use useEffect in my code?

After working with React Hooks for a few months and consistently using the useEffect hook based on the documentation, a new team member has raised questions about its necessity. Despite going over the documentation together, he believes that implementing u ...

What could be causing the onClick event handler to trigger twice in my create-react-app?

Does anyone know why the "upvote" onClick handler is triggering twice? Even though the logs show it's only running once, the score increases by 2 export default class Container extends Component { constructor(props) { super(props); this.sta ...

Efficiently map nested properties of this.props within the render method

When working in the render() method, I find myself passing numerous variables around. The recommended best practices suggest setting up variables before the return <div>...etc</div statement like this: const { products: mainProducts, ...

Invalid template detected within the Kendo dropdown component

I am trying to create a template that will only be displayed if the data value is "Low". This is how I have set up my template column: template: '# if( data=="Low" ){#<span><i class="fa fa-square blue"></i> <span># } ' U ...

Maximizing the width of navbar elements with Bootstrap 3

I am currently working on building a webpage with bootstrap3, but I have encountered an issue with the navigation bar. I would like the navigation links ("Web Design", "Development", "Photography", "Blog") to be evenly spaced out within the horizontal na ...

What is the best way to design unconventional grids using Bootstrap 4?

Is it possible to achieve unique grid layouts in Bootstrap 4? For instance, An irregular grid where the first column covers two rows, followed by two rows with three columns each |||||||||||||||| | | | | | | |_ |_ |_ | | | | | | |_____| ...

Trigger a click (or selection) on a specific dropdown option using jQuery

I am attempting to initiate a click function upon page load using jQuery on a dropdown option within Chosen, in order to activate a subsequent action. Unfortunately, I have not been successful in getting it to work. I have tried the following methods: jQ ...

What is the reason behind installing both Typescript and Javascript in Next.js?

After executing the command npx create-next-app --typescript --example with-tailwindcss my_project, my project ends up having this appearance: https://i.stack.imgur.com/yXEFK.png Is there a way to set up Next.js with Typescript and Tailwind CSS without i ...

Increasing the size of a background image as you scroll

Is there a way to adjust the background image of a div so that it scales according to the amount the page is scrolled? The current implementation works fine on desktop screens, but on mobile screens, the height of the background image reduces and the image ...

Is it necessary to de-duplicate the duplicated styles caused by Material-ui SSR Remix example after hydration?

I recently used the guide found at https://github.com/mui-org/material-ui/tree/master/examples/remix-with-typescript to integrate material-ui with SSR on Remix. However, I encountered an issue where duplicated styles appeared after hydration: https://i.ss ...

What specific type of useRef should I use to reference a callback function?

I have been exploring the method outlined by Dan Abramov for creating a custom hook to handle basic setInterval functionality. However, I am facing challenges while trying to type it in TypeScript. Specifically, I am unsure about what should be the type of ...

Working with HTML5 canvas to draw multiple images

Here is the code I'm working with: http://jsfiddle.net/zyR9K/4/ var Enemies = { x: 25, y: 25, width: 20, height: 30, speed: 0.5, color: "#000", draw: function () { canvas.fillStyle = ...

Retrieving data using a class in an AJAX form submission

I am attempting to use AJAX to submit an HTML form. Here is my HTML: <form class="lyrics"> <input type="text" value="" id="song" name="song"> <button type="submit" class="btn btn-info lirik">lyrics</button> </form> ...

Implementing long-lasting login functionality in React using JSON Web Tokens

Currently, I have developed an application using React client/Express API with functioning Authentication. Users are able to register and login successfully. My next step is to implement persistent login using JWT tokens so that when a user accesses the U ...