Using the "margin: auto" property to center the text box

  • I am having trouble centering the search box.
  • I tried adding marginLeft: "auto",marginRight: "auto" to the search class but it's not working.
  • Can you please advise me on how to fix this issue?
  • Below is my code snippet and a link to the sandbox:

https://codesandbox.io/s/material-demo-xu3ld

search: {
    marginLeft: "auto",
    marginRight: "auto",
    textAlign: "center"
  }

export default function CustomizedInputBase() {
  const classes = useStyles();

  return (
    <div className={classes.search}>
      <Paper className={classes.root}>
        <IconButton className={classes.iconButton} aria-label="Menu">
          <MenuIcon />
        </IconButton>
        <InputBase
          className={classes.input}
          placeholder="Search Google Maps"
          inputProps={{ "aria-label": "Search Google Maps" }}
        />
        <IconButton className={classes.iconButton} aria-label="Search">
          <SearchIcon />
        </IconButton>
        <Divider className={classes.divider} />
        <IconButton
          color="primary"
          className={classes.iconButton}
          aria-label="Directions"
        >
          <DirectionsIcon />
        </IconButton>
      </Paper>
    </div>
  );
}

Answer №1

Check out this sandbox.

Upon examining the resulting HTML code of your demonstration, it becomes apparent that the div where you applied the search class is indeed centered. However, the actual search element INSIDE the div is not aligned at the center.

Answer №2

Enclose your search query within a new div that has the class 'wrapper'

<div className={classes.wrapper}>
      <div className={classes.search}>
        <Paper className={classes.root}>
          <IconButton className={classes.iconButton} aria-label="Menu">
            <MenuIcon />
          </IconButton>
          <InputBase
            className={classes.input}
            placeholder="Search Google Maps"
            inputProps={{ "aria-label": "Search Google Maps" }}
          />
          <IconButton className={classes.iconButton} aria-label="Search">
            <SearchIcon />
          </IconButton>
          <Divider className={classes.divider} />
          <IconButton
            color="primary"
            className={classes.iconButton}
            aria-label="Directions"
          >
            <DirectionsIcon />
          </IconButton>
        </Paper>
      </div>
    </div>

and update your css with the following modifications.

  search: {
    textAlign: "center",
    display: "inline-block"
  },
  wrapper: {
    textAlign: "center",
  }

Answer №3

To easily center an element, flexbox is a great solution. Instead of relying on marginLeft and marginRight with auto values, you can achieve the same effect by using the following code:

styling: { display: "flex", justifyContent: "center" }

This will effectively center your desired element.

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

Tips for accessing the most recent embedded document added using the push() method

I'm having difficulty determining the feasibility of this situation. While using the mongoose blog example to illustrate, my specific use case is a bit more complex: var Comments = new Schema({ title : String , body : String , date ...

Display the current language in the Vue language dropdown

My component is called DropdownLanguage.vue Goal: I need to show the current active language by default in the :text="selectedOptionDropdown" attribute. For example, it should display "English" which corresponds to languages.name. I'm struggling with ...

modify style when not valid and is touched

When I try to modify the style of an i tag based on the touched and invalid state of another field, only the input tag's style changes and not the i tag. Here's the CSS code I'm using: input.ng-touched.ng-invalid { border-color: red; } ...

The window.open function is creating a new tab using the specified origin or URL

I have a button within an iframe on the webpage "loclahost:3000". When this button is clicked, it should open a new tab with the URL "www.google.com". However, instead of opening the desired URL, the new tab opens with the following incorrect URL: "http:// ...

Transmitting state to infinitely nested component in React/Redux

I'm currently facing an issue with a component that has children of the same type as itself in React with Redux. Although I can render the children, they are unable to access their own slice of state. export class Material extends React.Component { ...

I clicked on the Bootstrap Navbar button but unfortunately nothing occurred

I'm encountering an issue with my navbar. When the screen size is reduced, a button appears, but clicking it does not trigger any action. Here's my code; however, I'm unsure why the button in the Navbar isn't functioning as intended. ...

Differences between using Node.js with Express and EJS on Ubuntu and Raspbian systems

I've set out to create a small calendar using Express and EJS on Node.js. Everything was running smoothly on my laptop (Ubuntu). However, when I transferred the project to my Raspberry Pi to host the web server on my home network, an error was throw ...

How to prevent npm from being accessed through the command prompt

I recently began working on a ReactJs project. However, I am facing an issue where after starting npm in Command Prompt, I am unable to enter any text. Should I close the cmd window or is there a way to stop npm? You can now access your project at the fol ...

Performing a Protractor test on an Angular 5 application

We're in the process of transitioning our ui-library from AngularJS to Angular 5. I'm encountering challenges with the protractor tests. I need guidance on how to update the old AngularJS test to align it with Angular 5. If anyone has dealt wit ...

An error occurred during conversion: trying to convert an object to an array

After reading numerous articles about this issue and trying multiple solutions, I am still unable to resolve it! I have been stuck with this error for the past 3 days and I'm hoping someone can assist me. Thank you in advance for any help! My situati ...

Can someone explain how to trigger a JavaScript confirmation dialog box before the page loads in an ASP.NET application?

Below is the server side code snippet I am using: protected void Page_Load(object sender, EventArgs e) { if (Page.IsPostBack == false) { string confirmValue = Request.Form["confirm_value"]; if (confirmVal ...

What is the process for loading a JSON file using VueJS and Typescript?

I am facing an issue with loading a JSON file in my new VueJS project. Reproduction / Issue To easily reproduce the issue, I have created a Github repository: https://github.com/devedse/VueJSImportJsonFile In the Home.vue page, I am trying to get the JS ...

Prevent excessive clicking on a div element

I am facing a simple issue that I haven't been able to resolve yet. I want to prevent multiple clicks on a button before an AJAX call is complete. This is what I have tried so far: <button id="btn_pay"></button> $("#btn_pay").click( fun ...

Error encountered: The module '@mui/x-data-grid' does not export 'GridActionsCellItem'

I'm facing an issue while trying to import 'GridActionsCellItem' from '@mui/x-data-grid'. Here's the code: import { GridActionsCellItem } from '@mui/x-data-grid'; An error message pops up indicating: Attempted impor ...

What is the best way to call a method of a JavaScript object after calling a different method?

Upon frequently encountering this jQuery code snippet, I decided to simplify it into one level action as illustrated in the following code. function $(id) { var $ = document.getElementById(id); $.action1 = function() { }; return $; } Now ...

Using gridstack-angular.js with the Hot Towel Template: A Comprehensive Guide

I recently started using the Hot Towel Template and decided to incorporate the gridstack-angular package. I am attempting to implement the demo functionality into my-page.controller.js, my-page.route.js, and my-page.html. After loading the dependencies wi ...

What are some ways to personalize column design when a Kendo grid column is automatically created?

I am populating the Kendo grid with data using JavaScript: var dataSource = new kendo.data.DataSource({ transport: { read: { url: "@Url.Action("GetProductList", "Home")", type: "POST&qu ...

The node server.js encountered an error - Module not found

After attempting to start my node server using the following command: node server.js An error was thrown: internal/modules/cjs/loader.js:905 throw err; ^ Error: Cannot find module 'fcc-express-bground' Does anyone have any solutions? ...

Unable to scroll when utilizing ng-html-bind functionality

My device specifications: $ ionic info Your system details: Cordova CLI: 6.2.0 Gulp version: CLI version 3.9.1 Gulp local: Ionic Framework Version: 1.2.4 Ionic CLI Version: 2.0.0 Ionic App Lib Version: 2.0.0-beta.20 OS: Distributor ID: LinuxMint Desc ...

The behavior of the div element is not as expected when using "<select>", but it functions properly when using "<input>"

I found this code snippet on http://jsfiddle.net/Lijo/PJcZQ/. It features two divs labeled "GROUP1" and "GROUP2" with slightly different content. GROUP 1 <div class="secondTextBox"> <select name="ctl00$detailContentPlaceholder$ddlStatus" id= ...