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: https://i.sstatic.net/yZYKe.png

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

What method can be used to dynamically resize two side-by-side iframes in proportion to a specific ratio?

Hey, I've got this code snippet: So there are two iframes positioned side by side with a specific ratio as indicated in the link provided. My aim is to maintain that ratio regardless of the screen size where it's viewed. The first iframe is named ...

What is the best way to retrieve a state variable within the getServerSideProps() function in NextJS?

Introduction Greetings everyone, I am a newcomer to NextJS. Currently, I am in the process of developing a weather application that utilizes external APIs. My main task involves fetching data from an API and displaying it on the frontend. Desired Function ...

Attempting to superimpose a CSS triangle arrow onto a Google Map

I'm currently working on incorporating a CSS arrow on top of a Google map as a design element. The concept involves a horizontal stripe with a downward arrow placed halfway through, and I aim to have this arrow overlay the Google map. Here is a snipp ...

Guide on combining vendor CSS files in a React application using Webpack

Incorporating third-party libraries is an essential part of my project. For example, I have Mapbox GL installed via npm, which comes with CSS files needed for its functionality. The Mapbox GL CSS file can be found at mapbox-gl/dist/mapbox-gl.css in the no ...

What is the best way to center text vertically in a <div> using CSS?

This is my first attempt at creating a chrome extension, and I am currently working on centering text. Right now, I am using text-align: centre; to align the text horizontally, but I am struggling to figure out how to align it vertically. As a result, my t ...

Ways to adjust the view of a React Vis.JS Network Graph: How to zoom in or out

Hey there, I've set up my Network Graph with the following configuration: const exceptionsGraph = { nodes: graph, edges: edges } // Graph Options const options = { height: "80%", width: "100%", node ...

Resizing the window causes divs to be positioned relative to the image (almost functional)

In my coding project, I've encountered a situation where I have 3 "pins" positioned within a div called #outerdiv. This div has a background-image and the pins are supposed to remain in the same spot on the background image no matter how the window is ...

Choosing HTML elements within nested DIV tags

In the process of creating a Hangman-style game using javascript/jQuery, I encountered an issue with selecting HTML content from virtual keyboard keys : <div class="square keyboard"> <div class="content"> <div class="table"> ...

Enable scrolling exclusively for the content within a tab, without affecting the tab label in Clarity Tabs

I have a tab with lengthy content in my project (check out the StackBlitz reference here). This causes the appearance of a scroll. https://i.sstatic.net/ZcNKM.png The corresponding code snippet is provided below: <div class="content-container&qu ...

Personalize the tooltip for a MUI X Charts visualization

I am working on creating a line chart that displays distance versus elevation using GeoJSON data, and I need to customize the tooltip's appearance and content. Specifically, my questions are: How can I position the tooltip beneath the graph in a mor ...

Use React hooks to submit a form after updating the state

Seeking guidance on utilizing the latest react hooks. How can I update the state and then proceed to submit a form? For instance, I have a search box that relies on the typical state managed by setSearch, where upon submission, it queries data from the se ...

Should developers avoid using jQuery in ReactJS applications?

While working on a ReactJS project (or any other project), I personally prefer using pure JavaScript over jQuery. Lately, I've started questioning whether it's considered bad practice to use jQuery in ReactJS. Back when I was learning ReactJS, I ...

What could be causing the custom theme values to fail in my React component using Material UI v5?

I've set up a custom theme for MUI, but it doesn't seem to be functioning properly. I went through the steps carefully and double-checked everything to ensure it's all in order. Take a look at my package.json: "dependencies": { ...

hover effect with fading transition while mouse is still hovering

Is there a way to create a fade-in/fade-out effect on a div without the mouse needing to leave the area? Let me provide a clearer explanation: When the mouse enters the object The object gradually fades in Then, after a delay, the object fades out while ...

Configuring a background logo in WordPress using the Redux framework

I am attempting to integrate a "Logo upload" theme option using Redux framework, but I encountered an issue due to the logo being set up through a stylesheet in my HTML template. How can I configure this logo using an uploader? As a newcomer to WordPress a ...

What is the best way to capture a React login request in action?

After creating a sign up and login form in React, I am now looking to register users in a MongoDB database. I have attempted searching for tutorials on YouTube, but I am struggling to find one that explains how to implement this using the MERN stack. Sinc ...

Responsive Container MUI containing a grid

I am attempting to replicate the functionality seen on YouTube's website, where they dynamically adjust the grid layout based on the container size when a Drawer is opened or closed. Essentially, it seems that YT adjusts the grid count based on the c ...

Trouble arises when jquery's "position().top" clashes with the CSS3 property "transform: scale()"

Currently, I am working on adding a font resizer feature to my editing tool. To implement this, I made some changes to the text elements where their origin is now set to the bottom left corner. The normal version of the tool works perfectly fine, but when ...

Issues with the functionality of React Route v4.1.1 on the web platform

Upon receiving some suggestions, I made changes to my original code. Here is what my index.js file looks like now: import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import registerServiceWo ...

Is there a way to delete highlighted text without using execCommand and changing the font color

With my current use of JavaScript, I am able to highlight or bold a selected text range successfully. However, I am unsure how to undo the bold and unhighlight the text if the button is clicked again and the selected range is already bolded or highlighted. ...