How to Center Title Horizontally with Material-Ui and Custom Styling

I'm trying to horizontally align the title Hello John Joseph Jones at the top inside the black box, but it's taking up too much vertical space. I'm not sure if my code is correct, so any suggestions for improvement are welcome.

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

You can view the Codesandbox version HERE

  <Box m={3}>
      <Grid
        container
        direction="column"
        className={classes.container}
        spacing={2}
      >
        {/* <h1>Hello John Joseph Jones</h1> */}
        <Grid item xs={6} className={classes.pictureSection}>
          <div className={classes.imageSection}>
            <img
              src="https://picsum.photos/id/237/200/300"
              className={classes.img}
              alt="no pic"
            />{"                                            }
            <p className={classes.precinctNo}>PR&nbsp; 4838390</p>
            <p className={classes.controlNo}>555555</p>
          </div>
        </Grid>

        <Grid item xs={6} className={classes.nameAddressSection}>
          <Box className={classes.fontText}>John Joseph Jones</Box>

          <Box mt={1} className={classes.fontText}>
            26 South Hawthorne Drive Tonawanda, NY 14150
          </Box>

          <Box mt={1}>
            <QRCode size={80} value={"4234432"} />
          </Box>
        </Grid>
      </Grid>
    </Box>

Answer №1

Your Code has been successfully modified:

Added a new h1 tag, applied styling, and switched the Grid direction from column to row.

import React from "react";
import { makeStyles } from "@material-ui/styles";
import { Box } from "@material-ui/core";
import Grid from "@material-ui/core/Grid";
import QRCode from "react-qr-code";
import { red } from "@material-ui/core/colors";

const useStyles = makeStyles(() => ({
  button: {
    color: "white"
  },
  hideButton: {
    visibility: "hidden"
  },
  imageSection: {
    display: "flex",
    flexDirection: "column",
    justifyContent: "center",
    height: "100%"
  },
  img: {
    height: "4cm",
    width: "4cm",
  },
  h1: { // new
    fontSize: "0.70rem",
    width: "100%",
    textAlign: "center",
    margin: "0.1rem"
  },
  precinctNo: {
    display: "flex",
    justifyContent: "center",
    margin: "0",
    fontSize: "0.70rem",
    fontWeight: "bold",
    textTransform: "uppercase",
    color: "#000"
  },
  controlNo: {
    display: "flex",
    justifyContent: "flex-start",
    margin: "0",
    fontSize: "0.70rem",
    fontWeight: "bold",
    textTransform: "uppercase",
    color: "#000"
  },
  boxBorder: {
    border: "3px solid black"
  },
  container: {
    width: "8.5cm",
    height: "5.5cm",
    borderRadius: "3px",
    border: "3px solid #000000",
    color: "#00000"
  },
  pictureSection: {
    display: "flex",
    flexBasis: "100%"
  },
  nameAddressSection: {
    display: "flex",
    flexDirection: "column",
    textAlign: "center",
    flexBasis: "100%",
    justifyContent: "space-between"
  },
  alignItems: {
    alignSelf: "center",
    textAlign: "center"
  },
  fontText: {
    color: "#000000",
    fontSize: "0.70rem",
    fontWeight: "bold",
    textTransform: "uppercase"
  }
}));

const SampleCard = () => {
  const classes = useStyles();

  return (
    <Box m={3}>
      <Grid
        container
        direction="row" // new
        className={classes.container}
        spacing={2}
      >
        <h1 className={classes.h1}>Hello John Joseph Jones</h1> // new
        <Grid item xs={6} className={classes.pictureSection}>
          <div className={classes.imageSection}>
            <img
              src="https://picsum.photos/id/237/200/300"
              className={classes.img}
              alt="no pic"
            />{" "}
            <p className={classes.precinctNo}>PR&nbsp; 4838390</p>
            <p className={classes.controlNo}>555555</p>
          </div>
        </Grid>

        <Grid item xs={6} className={classes.nameAddressSection}>
          <Box className={classes.fontText}>John Joseph Jones</Box>

          <Box mt={1} className={classes.fontText}>
            26 South Hawthorne Drive Tonawanda, NY 14150
          </Box>

          <Box mt={1}>
            <QRCode size={80} value={"4234432"} />
          </Box>
        </Grid>
      </Grid>
    </Box>
  );
};

export default SampleCard;

Please pay attention to any potential implications of the comments in your return statement. (They may impact your application)

Answer №2

To achieve this, make some adjustments to the layout structure

Introduce a root class to serve as the main container

root: {
    width: "8.5cm",
    height: "5.5cm",
    border: "3px solid #000000",
    borderRadius: "3px",
    boxSizing: "border-box"
  },

Remove the border styling from the container class

  container: {
    color: "#00000",
    height: "100%"
  },

Apply these changes to the parent element

<Box className={classes.root} m={3}>

Add the centered text

<Box mb={1} className={classes.fontText} align="center">
        Hello John Joseph Jones
</Box>

Refer to https://codesandbox.io/s/material-ui-forked-dvoun?file=/SampleCard.js:197-252 for an example

In the provided example, padding is added to the parent element as it now contains the border, there are alternative methods to maintain the style

For keeping a fixed size, experiment with different configurations of the elements

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

Is there a way to customize Border Colors for ToggleButton in material ui?

I have a project that requires your assistance, and I have made several modifications to the code related to ToggleButton styling. Here is the updated code: const GenderBoxStyle = styled(ToggleButtonGroup)(({ theme }) => ({ flexDirection: 'row&ap ...

Integrating external JavaScript widgets into the web application in real-time

I am currently engaged in a React js project that involves the dynamic addition of third party scripts (widgets) to the web app. These widgets encompass various third party platforms such as Twitter, Instagram, Youplay, Youtube, and more. The existing co ...

When the menu is unfurled, the image descends gracefully

.nav-btn { display: block; background-color: #000; color: #FFF; font-size: 1.5em; /*text-align: right;*/ /*right: 2%;*/ float: right; cursor: pointer; padding-top: 20px; /*posi ...

Incorrect legend colors in Highcharts pie chart

[![enter image description here][1]][1] There seems to be an issue with the Pie-Chart where the Slice color and the Legend color do not match when the color is set using className. This problem does not occur with some other charts. If you look at the co ...

Utilizing React JS for Managing Multiple Modals

Hey there! I'm currently in the process of learning React and I have a question regarding creating multiple modals with the same design but different content. Can anyone help me out? import './Works.css'; import React, { useState } from &apo ...

Issue: Using the useParams() hook triggers a TypeError, stating that useContext(...) is undefined

Having trouble with the useParams() react hook to fetch a parameter, and encountering this error: Error: useContext(...) is undefined The hooks file throws this error on line 40: /modules/hooks.js:40 39 | > 40 | const match = useContext(Context) ...

After developing a React application to fetch data from my own API, I encountered the following error message: "TypeError: video.map is not a function". See the code snippet below:

import React, {useEffect, useState} from "react"; import Axios from "axios"; const VideoPage = () => { const [video, setVideo] = useState(null); const [loading, setLoading] = useState(true); useEffect(() => { const fetchVideoData = async() =&g ...

Moving Images from Firebase to Google Drive

I'm looking for a way to automatically copy photos uploaded to a Firebase DB to a designated Google Drive folder. Is there a way to achieve this while the photos are getting uploaded to Firebase or once the last photo is uploaded? The link below seems ...

When utilizing the "as" attribute, styled components do not inherit any styles

I am currently utilizing both styled-system and styled components, working on a simple scenario like the one below: const buttonFont = { fontFamily: "Chilanka" }; // define basic text styling const Text = styled.div` ${typography} ${color} `; // c ...

Animate custom scrollbars with jQuery for a unique browsing experience

I am experimenting with creating a scrolling animation using mCustomScrollbar Currently, I have managed to obtain the current scrollTop and animate it to a specific height using the code below: $("#content").mCustomScrollbar({ scrollButtons:{ ...

Utilize Jquery Mobile ThemeRoller's design on your MVC4 mobile app for a cohesive and professional look

After creating an MVC4 Mobile application in Visual Studio 2013, I am struggling to apply jquery mobile themeroller themes to it. I attempted to replace the existing theme css with my custom theme, but it does not seem to be working at all. See the code ...

The Angular Shepherd Tour Guide is experiencing a bug where it does not scroll when the next page is clicked

I'm facing an issue where scrolling to the next element is not working properly. When I click on the next element, it moves there but does not scroll down automatically. I have tried various solutions but have been unsuccessful so far. If anyone can p ...

Enhance your PrimeNG p-calendar by customizing the background-color of the dates

Hello, I am currently attempting to customize the appearance of the p-calendar, but I am struggling with changing the color of the displayed dates. Can anyone provide assistance? Thank you in advance. Below is my template: <div class="p-field p-co ...

How to make Firefox create a new line in a contenteditable field

I am working with a contenteditable div that is within a parent div with a floating width of 50%. My goal is to set the max width of the content editable to match the container, even if the text spans multiple lines. Here is the CSS I tried: .editable-con ...

Enhance your React Native app: Utilizing dynamic string variables with react-native-google-places-autocomplete query

I have encountered an issue while attempting to pass a dynamic country code to restrict search results. Here is the code in question: let loc = 'de' <GooglePlacesAutocomplete placeholder="Search" autoFocus={true} onPress ...

What is the best technology to implement for a band website design?

I'm in the process of creating a website for my friend's band, and I need some creative input. The site will feature minimal content such as a bio, news, and embedded audio/visual material. While my web development skills are decent, I'm loo ...

Creating a line that extends from the left side of the viewport to the full length of an element within a bootstrap column

I'm currently working on creating a title that has a unique design: https://i.sstatic.net/VhEBQ.png The design requires a horizontal line to start from the left side of the viewport and end at the same point where the title ends. I am aiming to keep ...

What is the best way to align the logo image to the left side of the Material UI app bar without any gaps?

Currently, I am working on a material UI app bar to serve as my navigation bar. The issue I am encountering involves the logo image on the left side of the page having excessive spacing from the edge, as shown in the image below. I've tried adjusting ...

Is there a downside to concealing a checkbox off-screen using position: absolute for a clever workaround?

I recently came across a clever trick known as the checkbox hack, which involves hiding checkboxes on web pages by positioning them off-screen. The example provided on CSS Tricks demonstrates this technique with the following code: position: absolute; top ...

Unable to retrieve custom date picker value with React Antd

I have implemented a custom datepicker for entering dates in the 'MMDD' or 'MMDDYY' format. The date value is stored in state and used in the datepicker component as a controlled component. However, upon form submission, the datepicker ...