Enhance your Material UI Button with Advanced Text Alignment Options for Compact Screens

As a beginner in React and Material-UI, I'm attempting to customize a set of buttons within my app bar with background images for a cleaner look. Drawing inspiration from various online examples, I've managed to style them to my liking on larger screens (md++). However, upon resizing to a smaller breakpoint, the button images start stacking vertically (which is desired) but the accompanying text shifts to the left. Despite my efforts to adjust the alignment to the right, it doesn't seem to be the correct approach. Is there a specific way to make the text flexible so that it stays centered?

import React from 'react'

import { AppBar, Toolbar } from "@mui/material";
import { makeStyles } from '@mui/styles'
import Button from '@mui/material/Button'
import Stack from '@mui/material/Stack'
import ButtonBase from '@mui/material/ButtonBase';
import { styled } from '@mui/material/styles';
import Typography from '@mui/material/Typography';
import Box from '@mui/material/Box';

const useStyles = makeStyles(theme => ({

    button: {
        ...theme.typography.mainmenu,
        borderRadius: "40px",
        marginLeft: "1px",
        height: "45px",
        "&:hover": {
            backgroundColor: theme.palette.secondary
        }
    },

}))

const images = [
    // Image data omitted for brevity
];
const Image = styled('span')(({ theme }) => ({
    // Styles for image span
}));

const ImageButton = styled(ButtonBase)(({ theme }) => ({
    // Styles for image button
}));

const ImageSrc = styled('span')({
    // Styles for image source
});
const ImageBackdrop = styled('span')(({ theme }) => ({
    // Styles for image backdrop
}));

const ImageMarked = styled('span')(({ theme }) => ({
    // Styles for image marked
}));

const Header = () => {
    const classes = useStyles();
    return (<React.Fragment><AppBar position="sticky" className={classes.appBar}>
        <Toolbar disableGutters className={classes.mainToolbar} sx={{ justifyContent: "center" }}>
            <Stack direction="row" justifyContent="space-between" alignItems="center" spacing={10}>
                {/*  Buttons content */}
                <Box sx={{ display: 'flex', flexWrap: 'wrap', minWidth: 900, width: '100%' }}>
                    {images.map((image) => (
                        <ImageButton
                            focusRipple
                            key={image.title}
                            style={{
                                width: image.width,
                            }}
                        >
                            <ImageSrc style={{
                                backgroundImage: `url(${image.url})`
                            }} />
                            <ImageBackdrop className="MuiImageBackdrop-root" />
                            <Image>
                                <Typography
                                    component="span"
                                    variant="subtitle1"
                                    color="white"
                                    fontWeight="bold"

                                    sx={{
                                        position: 'relative',
                                        p: "7em",
                                        pt: "2em",
                                        pb: (theme) => `calc(${theme.spacing(1)} + 6px)`,
                                    }}
                                >
                                    {image.title}
                                    <ImageMarked className="MuiImageMarked-root" />
                                </Typography>
                            </Image>
                        </ImageButton>
                    ))}
                </Box>
            </Stack>
        </Toolbar>
    </AppBar>

    </React.Fragment >
    )
}

export default Header

Answer №1

Although I have moved past this stage, for those who stumble upon it, I successfully revamped my application using MUI with the following approach:

import useMediaQuery from '@mui/material/useMediaQuery'

along with examples like:

const matches = useMediaQuery(theme.breakpoints.down("md"))

to dynamically adjust the styles of the application based on screen size

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 could be causing my React function to move forward without waiting for the SweetAlert confirmation?

I'm having an issue with the swalDelete function in my code. After clicking the 'Delete' button, the 'doDelete' log appears immediately instead of waiting for a response from SweetAlert. How can I modify it to wait for a response? ...

What are some ways to accomplish this task without relying on a photo editing tool?

Is it possible to swap the image link: with this new link: without having to use a photo editor? Below is the CSS and HTML code: I was unable to upload the logo due to the restriction of needing at least 10 reputation points in order to post more t ...

Highlighting table column when input is selected

I am working with a table where each <td> contains an <input>. My goal is to apply the class .highlighted to all the column <td>s when an <input> is being focused on. Additionally, I want to remove this class from all other columns ...

I encountered an issue where the data I passed to a component ended up being undefined

So here's the scenario: I'm working on a Next.js project where I have a context for modals. In this context, I store modal details in an array called modalBase. Additionally, I fetch data from another context (toolsContext) to pass it to componen ...

Encountering an Invariant Violation error while converting app.js from create-react-app to react native

I initially developed my project using create-react-app but decided to switch to react native for publishing purposes. To do this, I created a new project in react native and then transferred my app.js file over. However, I encountered an error message: ...

Create a border that does not inherit the opacity of the object

Check out this jsBin for reference: http://jsbin.com/uyonux/1 The hover state is working fine, but the focus state is not. I want the blue color to remain solid #13A3F7 without inheriting the opacity of .4. Is there a way to achieve this without the elem ...

Arranging numerous Text elements within a solitary Drag and Drop container with the z-index property

I am facing a challenge with stacking twelve arguments in no particular order on a drag and drop element. The texts overlap each other, making it difficult for the end user to see them clearly when dragging and dropping. Is there a way to stack texts using ...

Which repository is generating this error message?

After discovering an error message, I'm curious to know which repository is responsible for its creation. My intention is to submit a PR to update it. Despite cloning the create-react-app and Babel repositories, I was unable to find any results usi ...

NodeJS rendering method for HTML pages

We are in the process of developing a fully functional social networking website that will resemble popular platforms like Facebook or Instagram. Our plan is to utilize Node.js on the server side and we are currently exploring the best technology for rende ...

What steps need to be taken to set up Node.js to accommodate requests from external sources beyond just localhost?

After creating an application using NextJs, I successfully built it and ran it on a node server by executing 'npm run start' in Powershell. Everything works perfectly when accessing it locally through port 80. However, my Windows Server 2019 does ...

Setting the path to an image component using the style jsx tag in Next.js: A step-by-step guide

While utilizing jsx to define styles for my NextJs components, I am facing the challenge of defining a background image for certain elements. I have realized that only relative paths or absolute paths are accepted. But how can I pass a relative path to th ...

Execute function upon initial user interaction (click for desktop users / tap for mobile users) with the Document Object Model (DOM)

Looking to trigger a function only on the initial interaction with the DOM. Are there any vanilla JavaScript options available? I've brainstormed this approach. Is it on track? window.addEventListener("click", function onFirstTouch() { console.l ...

Various background positions

Is it possible to declare multiple background positions for the same background image? I have a span with the class page_heading and I want this class to display the same image twice, once at the beginning of the text and once at the end. HTML: <h1&g ...

Ways to prevent styles from being overridden by those specified in JavaScript

Some elements on my page have their style dynamically changed by JavaScript. However, I want one of them to maintain its static style without being overridden. Is there a way to specify that the style of this particular element should not be altered? Than ...

design facebook type box scroll bar

After extensively searching through various stackoverflow answers in an attempt to change the CSS for a Facebook likebox scrollbar, I have had no success. Below is the code that I am currently using: <div id="fb-root"></div> <script>(fun ...

``The background color will dynamically change according to the result of a function

My function named shift_color generates different color codes like "#FF5F74", "#5FFF66", and "#5F8AFF". I am looking to use this output to style a navigation menu background. I have tried the following code: .topnav { background-color: <?php echo shi ...

Protecting the build directory while implementing actions/checkout@v2

My self-hosted GitHub runner is configured to deploy a Next.js app by checking out the repository, building, and restarting pm2. The issue arises when the actions/checkout@v2 step triggers, as it deletes all files in the repository, including the crucial ...

Bootstrap Model Footer Button Alignment

click hereI'm facing an issue while adding buttons to the model footer. The buttons are not aligning in line, instead they move to the next line. <div class="modal-footer"> <form method="post" action="admin_view"> ...

Utilize Material UI's makeStyles to apply styles to a component with the attribute aria-checked set to "true"

I would like to customize the appearance of a checkbox (not using Material-UI checkbox) by utilizing its aria-checked="true" attribute with makeStyles. In the Material-UI documentation, I noticed that pseudo selectors can be styled like this: '&: ...

The value property of the input element is returning as undefined

The input value entered is always returning undefined. Despite trying various solutions found in similar questions, my jQuery code continues to return undefined. jQuery: $( document ).ready(function() { $('#Input').keypress( function(e ...