How to centrally align a component in React (both horizontally and vertically)

I am currently implementing React with Bootstrap in my project.

Here is the render function I have been working on, with the goal of center aligning the form.

render() {
    return (
        <div class="row">
            <div className="col-md-3 center">
                <form>
                    <div class="form-group">
                        <label for="exampleInputEmail1">Email address</label>
                        <input value={this.state.email} onChange={this.handleChange} type="email" name="email" class="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email" />
                        <small id="emailHelp" class="form-text text-muted">We'll never share your email with anyone else.</small>
                    </div>
                    <div class="form-group">
                        <label for="exampleInputPassword1">Password</label>
                        <input value={this.state.password} onChange={this.handleChange} type="password" name="password" class="form-control" id="exampleInputPassword1" placeholder="Password" />
                    </div>
                    <button type="submit" onClick={this.login} class="btn btn-primary">Login</button>
                    <button onClick={this.signup} style={{ marginLeft: '25px' }} className="btn btn-success">Signup</button>
                </form>
            </div>
        </div>


    );
}

Here is the styling for the center class:

.center {
    display: flex;
    justify-content: 'center';
    align-items: 'center';
}

https://i.sstatic.net/yz7Ii.png

However, the output is not as expected. The form remains on the top-left corner despite the styling. I believed this approach would work.

UPDATE

form {
    background: #55acf3;
    padding: 1.5em;
    border-radius: 1em;
}

.center {
    display: flex;
    justify-content: center;
    align-items: center;
}

.error-message {
    margin-top: 1em;
    color: red;
}

Answer №1

update the CSS by including the height property

.center {
    display: flex;
    justify-content: center;
    align-items: center;
    height:100vh;  
}

https://jsfiddle.net/132y89rc/

Answer №2

To ensure proper alignment in your JSX rendering, it is recommended to always use className instead of class. Additionally, include the following styles for horizontal and vertical alignment: margin: 0 auto for horizontal alignment, and height: 100vh and align-self: center for vertical alignment. This setup should effectively align your elements.

Outlined styles:

.d-flex {
  display: flex!important;
  height: 100vh;
}

.center {
  margin: 0 auto;
  align-self: center;
}

Component structure:

render() {
        return (
          <div className={`row ${styles['d-flex']}`}>
            <div className={`col-md-3 ${styles.center}`}>
              <form>
                <div className="form-group">
                  <label htmlFor="exampleInputEmail1">Email address</label>
                  <input value={this.state.email} onChange={this.handleChange} type="email" name="email" className="form-control" id="exampleInputEmail1" aria-describedby="emailHelp" placeholder="Enter email" />
                  <small id="emailHelp" className="form-text text-muted">We'll never share your email with anyone else.</small>
                </div>
                <div className="form-group">
                  <label htmlFor="exampleInputPassword1">Password</label>
                  <input value={this.state.password} onChange={this.handleChange} type="password" name="password" className="form-control" id="exampleInputPassword1" placeholder="Password" />
                </div>
                <button type="submit" onClick={this.login} className="btn btn-primary">Login</button>
                <button onClick={this.signup} style={{ marginLeft: '25px' }} className="btn btn-success">Signup</button>
              </form>
            </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

Activate a CSS button upon clicking and update the content within the div

In order to achieve the desired result of having menu CSS buttons change the content of a div when clicked, I have managed to do that successfully. However, a problem arises when clicking on the 2nd or 3rd button/link - it changes the div content, but as s ...

Having trouble establishing a connection between the client and server while using Node.js with socket.io, Express, and an HTML file

While following a tutorial on YouTube for creating a simple web game with lobbies/rooms, I encountered an issue. When attempting to establish a connection between the client and server, the expected "a user connected" text did not show up in the console as ...

Adjust image size to maintain consistent dimensions

Is there a way to resize the images so they maintain the same aspect ratio? Currently, all the images are appearing distorted. https://i.sstatic.net/czpto.png Here is the HTML code for the card: <div class="container"> <div class="flex- ...

Circular gradient backdrop

Looking to create a sleek and professional body background for my website that is as attractive as Twitter's. Can you help me achieve the same blue shaded background effect? I'm new to web development and would appreciate any guidance on how to m ...

Div expanding beyond intended size when media reaches maximum 468 pixels

When zoomimg is set to width: 145px; height: 145px; it ends up pushing the text that should be inside its parent element out of the parent. If you want to see the Zoomimg ProjectKort divs, check out the code below: .projectkort{ margin: 10px 0px 10px 0 ...

The issue with EJS Header and Footer not showing up on the

I am currently building a basic todo list application using EJS. However, I am encountering an issue when running it. I would like to run app.js with the header and footer in EJS, but it seems that it is not recognizing the header despite using what I beli ...

The radio button fails to register the selection

I need to ensure a radio button is checked if it has a value, but the output of my code is not displaying as expected: <input id="radio2" type="radio" checked="checked" value="2" name="radio"> Despite specifying checked="checked", the radio button ...

Easily include the header component in all other components using React Router 4.1.1 without the need to import it

I have been searching for documentation on nested routes in version 4.1.1 of React Router on the website https://reacttraining.com/react-router. Unfortunately, I have not been able to find a solution. In older versions of React Router, nesting Routes was d ...

Sort elements based on the chosen option in the select component

Here's a link to my app on Codesandbox https://codesandbox.io/s/filter-search-gxidc?file=/src/App.js which consists of only one component, app.js Within data.js, I have an array of objects: export const data = [ { currencies: [{ code: "AFN ...

Updating Django database records with ajax

I'm currently working on a feature that involves filtering table data and updating the table using ajax. Here's what I have so far: Filter Form: <form id="search" method="POST" action="{% url 'article-filter' %}"> <input ...

What could be causing my jQuery search feature to only function properly one time?

This is a code snippet that can search for, scroll to, and highlight a specific piece of text on a webpage. For the code demo, you can check it out on jsFiddle: http://jsfiddle.net/z7fjW/137/ However, there seems to be an issue with the functionality. Af ...

After several interactions, the CSS files fail to load

I'm currently utilizing jQuery Mobile with 3 pages, and I've noticed that after navigating between the pages, the CSS is not being rendered properly. LoadCss.js $(document).on("pageinit",function(event) { $("#categoriesPage").on('pages ...

Using curly brackets as function parameters

Can someone help me understand how to pass an emailID as a second parameter in curly braces as a function parameter and then access it in AccountMenuSidebar? I apologize for asking such a basic question, I am new to JavaScript and React. class Invoices ex ...

Tips for centering or aligning a component to the right using Material UI?

Is there an efficient method to align my button to the right of its parent in Material UI? One approach could be using: <Grid container justify="flex-end"> However, this would also require implementing another <Grid item />, which m ...

Removing fragment identifier from the URL

If you go to stackoverflow.com/#_=_, the expression window.location.hash will display #_=_. All good so far. But when you run window.location.hash = '' to get rid of the hash, the URL changes to stackoverflow.com/#. (Note the unexpected # at the ...

What is the best way to center a button element horizontally within a div element?

I am looking for a way to center a button horizontally without adding CSS directly to the div element (for example, using <div style="text-align: center;">). My goal is to apply CSS code specifically to the button element. <div> <butto ...

Ways to assign the value of an alert to an element

Within this piece of code, my intention is to retrieve the alert value and apply it to an element. Description: The AJAX code I have written checks for values in a database, fetches new values from the database, and then displays these fetched values in a ...

Is there a way I can ensure the values are loaded when the page loads, rather than displaying NaN?

I've recently created a car rental calculator for a client, and it's almost complete. Everything is working smoothly, from the calculations to the conditions. However, I'm facing an issue where the price isn't calculated on page load. I ...

Reducing Bootstrap Navigation Bar with a scrolling logo

Is there a way to make the fixed navbar shrink 50% when it starts scrolling? I've only come across text navbars, but I'm looking for one with a logo. Any suggestions would be greatly helpful. You can access the css and html from that link. ...

What is the process for changing and updating the key of an object based on comparisons with other objects?

My task involves working with an array of objects that contain unique IDs as keys. const sampleObj1 = {0011:[{},{}], 0022:[{}, {}], 0033:[{},{}]} const sampleObj2 = [{id:0011, name:'test1'}, {id:0022, name:'test2'}, {id:0033, name:&apos ...