Centralizing the Accordion header and expansion icon in React with Material-UI

I'm currently incorporating the Accordion feature from Material-UI library into my React project:

My goal is to ensure that the accordion summary (header with "Accordion 1", "Accordion 2") is centered, and the expand icon (arrow) is also centered right below it.

Upon checking the Material-UI documentation (https://material-ui.com/components/accordion/), the layout displayed resembles as shown in the image below:

The code snippet provided in the documentation looks like this:

import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Accordion from '@material-ui/core/Accordion';
import AccordionSummary from '@material-ui/core/AccordionSummary';
import AccordionDetails from '@material-ui/core/AccordionDetails';
import Typography from '@material-ui/core/Typography';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';

const useStyles = makeStyles((theme) => ({
  root: {
    width: '100%',
  },
  heading: {
    fontSize: theme.typography.pxToRem(15),
    fontWeight: theme.typography.fontWeightRegular,
  },
}));

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

  return (
    <div className={classes.root}>
      <Accordion>
        <AccordionSummary
          expandIcon={<ExpandMoreIcon />}
          aria-controls="panel1a-content"
          id="panel1a-header"
        >
          <Typography className={classes.heading}>Accordion 1</Typography>
        </AccordionSummary>
        <AccordionDetails>
          <Typography>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse malesuada lacus ex,
            sit amet blandit leo lobortis eget.
          </Typography>
        </AccordionDetails>
      </Accordion>
      <Accordion>
        <AccordionSummary
          expandIcon={<ExpandMoreIcon />}
          aria-controls="panel2a-content"
          id="panel2a-header"
        >
          <Typography className={classes.heading}>Accordion 2</Typography>
        </AccordionSummary>
        <AccordionDetails>
          <Typography>
            Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse malesuada lacus ex,
            sit amet blandit leo lobortis eget.
          </Typography>
        </AccordionDetails>
      </Accordion>
      <Accordion disabled>
        <AccordionSummary
          expandIcon={<ExpandMoreIcon />}
          aria-controls="panel3a-content"
          id="panel3a-header"
        >
          <Typography className={classes.heading}>Disabled Accordion</Typography>
        </AccordionSummary>
      </Accordion>
    </div>
  );
}

Thank you for your help!

Answer №1

Modifying the flex-grow property of the summary content to 0 instead of 1 seems to solve the issue:

import { withStyles } from "@material-ui/core/styles";
import MuiAccordionSummary from "@material-ui/core/AccordionSummary";
const AccordionSummary = withStyles({
  content: {
    flexGrow: 0
  }
})(MuiAccordionSummary);

https://codesandbox.io/s/centered-accordionsummary-5iokp?fontsize=14&hidenavigation=1&theme=dark

If you prefer having the arrow centered below the summary text (instead of beside it like in the initial example), you can use this code snippet:

const AccordionSummary = withStyles({
  root: {
    flexDirection: "column"
  },
  content: {
    marginBottom: 0
  },
  expandIcon: {
    marginRight: 0,
    paddingTop: 0
  }
})(MuiAccordionSummary);

https://codesandbox.io/s/centered-accordionsummary-forked-bz31k?fontsize=14&hidenavigation=1&theme=dark

This second illustration also highlights the utilization of a class for SimpleAccordion (as per the feedback) utilizing withStyles rather than makeStyles/useStyles for additional styling in the scenario.

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

I possess an array of objects that includes both images and documents. My goal is to examine the mime_type of each object and select the first element in React to be displayed within an <img> tag

I have an array of objects that contain images and documents. My goal is to display the first image only if the mime_type is 'image/jpeg' or 'image/png'. I am working with React. Despite my attempts, I keep encountering undefined resul ...

Is it possible that images appear normal locally, but become stretched once deployed? (CSS/HTML only)

I designed a straightforward webpage using only HTML and CSS. Everything looks great when I view it on my local machine. However, once I deployed the site on Droppages, a static-page hosting service integrated with Dropbox, all my images became stretched ...

What is the method for creating a transparent background for Material UI v1.0 Dialogs?

I'm attempting to place a CircularProgress component inside a dialog box. However, I'm facing an issue where the background of the dialog box is white and cannot be set to transparent like in previous versions of Material UI (v0.2). style={{ ...

In what ways does React outperform Angular 1.x?

After reading up on this, it seems like React aggregates all DOM changes before making them. Couldn't Angular employ a similar mechanism? It already knows which DOM nodes need to be altered after the digest cycle -- why not coordinate the updates alto ...

What could be the reason for the data being retrieved but not showing up on the web page?

When fetching data from an API, I encounter a problem where the Loader displays but the data never shows up on the page. The inconsistency of this behavior is puzzling to me. This issue seems to be more prevalent on smartphones than on computers. useEffec ...

ui-grid row size set to automatically adjust using rowHeight : 'auto'

Has anyone else experienced this strange behavior with ui-grid? When I set the rowHeight to auto, each cell in the same row ends up with different heights. One of the cells contains multiline data, which seems to be causing issues for ui-grid. I've ev ...

I am facing a problem with the code for my React login page and router

My form page is built in react and typescript, utilizing JWT tokens on the API side. While there are no issues with the container page, I encountered an error on the index.tsx page where the routers are defined: A TypeScript error occurred in C:/Users/yusu ...

The React application functions properly when initiated with `npm start`, but displays a 404 error after being built

I encountered an issue while developing a React App. Everything seemed to be working fine during the execution of `npm start`. However, after running `npm run build` and entering `serve -s build` in the terminal under the build folder, the browser displaye ...

What are some strategies to prevent prior asynchronous effects from interfering with a subsequent call to useEffect?

I have a straightforward component that initiates an asynchronous request when a certain state changes: const MyComponent = () => { const [currentState, setCurrentState] = useState(); const [currentResult, setCurrentResult] = useState(); useEffec ...

Eliminate the outline of the pager row in an asp.net grid view

Within my grid view, I have applied a bottom border to all cells. However, this border is also appearing on the pager row, which is not desired. To address this issue, I attempted to use jQuery to remove the border, but it seems that my selector is incorre ...

Aligning elements next to each other in html / css without using any top margins

How can I arrange four blocks of text side-by-side, center them over a background image, and ensure they respond well on different screen sizes without using tables? I typically use tables for this layout, but I've heard that CSS/HTML5 can achieve th ...

Tips on resolving the flickering issue in dark mode background color on NextJS sites

One problem I am facing is that Next.js does not have access to the client-side localStorage, resulting in HTML being rendered with or without the "dark" class by default. This leads to a scenario where upon page reload, the <html> element momentari ...

Variations in CSS display across various browsers

I'm currently facing an issue while learning web development. The expected result only appears when I preview my website on an old version of Internet Explorer, but it doesn't show up correctly when opened on Firefox or Chrome. The code I have i ...

Iterating through an SVG path multiple times

If I have the arrow below and I want to place it at various locations within the svg: <svg width="400" height="400"> <path transform="translate(150,100)" fill="black" d="M 0.5,0.5 l-100,0 -25,20 25,20 100,0 z" /> <path transform="translate( ...

Why is it important to incorporate the CSS property background-repeat: repeat; into our code?

It is believed that if you don't expressly mention the background-repeat in CSS styling, browsers will automatically set it as background-repeat: repeat. With this default behavior in place, one might wonder why there is even a need for a separate ba ...

The element's position remains unchanged after the .click re-event in the function

Welcome to my first attempt at using jQuery! Please bear with me as I navigate through this learning process. Here's the challenge: I have a series of elements in my HTML. <div class="garden"> <div class="point left">&#9668;</d ...

Struggling to align text to the far left within a text area using Bootstrap

When I accidentally place my cursor earlier in the text area, it starts writing from that point, leaving some unwanted spaces at the beginning. I prefer it to start from the extreme left, similar to how it behaves in input boxes. Below is the code snippet ...

What is the process for configuring electron-builder.js within the directory of my project?

image of my project's structure In my current project, I am combining electron and react to create an application. All the necessary settings for execution are specified in the package.json file. The code I have written is displaying as expected. H ...

How to manually highlight a row in Material UI's xgrid

As someone with 10 years of experience in HTML UI, I am new to Material UI and React. Currently, we are utilizing the XGrid component with rows and columns. The issue I am facing is that when hovering over rows, they highlight by turning light blue. Howeve ...

Styling CSS: Create circular images with dynamic text positioning or resizing on screens larger than 768px

I'm struggling to figure out how to create a circular profile picture on a background image that remains responsive and maintains its position across different screen sizes. Currently, I've been using fixed margin values to adjust the position, ...