A simple guide to positioning an image between two lines of text with Material UI

I am trying to design a banner area with an icon on the left and two lines of text (title and sub-title) in the middle. However, when I implement this structure, each element appears on a separate line.

You can view the issue here: https://codesandbox.io/s/bold-brook-71ucup?file=/src/App.js:366-402. To simplify things, I have replaced the icon area with text.

import { Grid, Stack, Typography } from "@mui/material";

export default function App() {
  return (
    <>
      <Grid container>
        <Grid item xs={12} direction="row">
          <Stack xs={3}>
            <Typography>Icon</Typography>
          </Stack>
          <Stack
            sx={{
              borderBottom: 1,
              borderColor: "grey.500",
              alignItems: "center",
              xs: 9,
              direction: "column"
            }}
          >
            <Typography variant="h5">My-Title</Typography>
            <Typography variant="h7" sx={{ fontStyle: "italic" }}>
              My-Subtitle
            </Typography>
          </Stack>
        </Grid>
      </Grid>
    </>
  );
}

I am struggling with using Material UI components like Grid, Box, and Stack effectively. I find it confusing knowing when to use them and which properties to apply. Even specifying columns for each item doesn't seem to work as expected. Any guidance on how to troubleshoot such problems would be greatly appreciated.

Update: I managed to resolve the issue by changing the <Grid item ...> to also be a container as <Grid item container ...>. This allowed me to correctly utilize the direction property within the container so that I could align the stacks side by side. The updated solution can be found in the sandbox.

Answer №1

To create a banner using Material UI, all you need is the stack and Alert components. Here's an example code:

<Stack sx={{ width: '100% }} spacing={2} >
  <Alert 
      severity="info" 
      sx={{ 
        fontSize: '14px'
        }}
    >
    ""Title and Subtitle will be here""
  </Alert>
</Stack>

Check out this Banner with a Todo addition

Before diving into creating banners, it's important to understand the concept of grids.

A grid is a two-dimensional flow that consists of rows and columns, allowing you to organize and layout your content effectively.

On the other hand, a box represents a one-dimensional system where you can specify your content in either a horizontal row or vertical column.

The Stack component is particularly useful for creating banners. Thank you.

Answer №2

Resolved by including the container attribute along with the item attribute in the grid structure. The issue stemmed from the two stacks being arranged vertically within the element, causing the direction attribute set to "row" to be disregarded. By introducing the container attribute, the direction attribute was properly recognized. Additionally, I eliminated the use of xs attributes on the stack components.

import { Grid, Stack, Typography } from "@mui/material";

export default function App() {
  return (
    <>
      <Grid container>
        <Grid
          item
          container
          xs={12}
          direction="row"
          sx={{ borderBottom: 1, borderColor: "grey.500" }}
        >
          <Stack sx={{ alignItems: "center" }}>
            <Typography>Icon</Typography>
          </Stack>
          <Stack
            sx={{
              alignItems: "center",
              direction: "column",
              flexGrow: 1
            }}
          >
            <Typography variant="h5">My-Title</Typography>
            <Typography variant="h7" sx={{ fontStyle: "italic" }}>
              My-Subtitle
            </Typography>
          </Stack>
        </Grid>
      </Grid>
    </>
  );
}

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

How can I attach a jQuery plugin to a textbox with a changing class name?

I have a function that converts a regular text field into a datepicker: <input type="text" class="datepicker form-control" name="text-150" > var DatePicker = function () { if ($(".datepicker").length === 0) { return; } $(".datepic ...

Vertical scrollbar in iframe unexpectedly appears immediately after the submit button is pressed

I have designed a contact form that is displayed in an iframe within an overlay div. I have carefully adjusted the dimensions of this div to ensure that there are no scrollbars visible when the form initially appears. However, after filling out the form an ...

Generating an array of keys from duplicated values in Typescript

My data is structured in the following array format: { itemTitle: 'value example', itemType: 'value example', itemDescription: 'value example', itemFamily: 'Asset', }, { itemTitle: 'val ...

obtainServerSideProps query parameter

Hey there, I'm trying to use NextJS and its getServerSideProps function to send an API Request, but I'm having trouble passing my ID Query Parameter along. The URL for my API is: http://localhost:3001/product/${id} Below is my code: const rout ...

Obtain the count of unique key-value pairs represented in an object

I received this response from the server: https://i.stack.imgur.com/TvpTP.png My goal is to obtain the unique key along with its occurrence count in the following format: 0:{"name":"physics 1","count":2} 1:{"name":"chem 1","count":6} I have already rev ...

show data pulled from localStorage

I'm struggling to figure out how to use localStorage for the first time, specifically in storing an array of objects and displaying that information even after page refresh. Currently, I can see that it is being stored but not displayed. const book ...

When using SweetAlert2, a single button will automatically be highlighted as soon as the modal opens

I recently made the switch from using SweetAlert to SweetAlert 2. It took some time to get used to, but I finally achieved my desired outcome, with one small exception. Upon opening the modal, if there is only one button and no other inputs, the button ap ...

What is the method to determine the size of a Map object in Firestore database?

I currently have two elements within a document: an empty array, and a map object containing three components. If the array is empty, it transforms into type array. In this case, I can execute console.log(vehicles.Motorcycles.length) to receive a return of ...

JavaScript - I have a variable trapped inside a function and I'm struggling to retrieve it

Is it possible that I'm missing something obvious here? I am really struggling to pass the 'body' variable out of this nested function. function retrieveFacebookInfo(userID) { request({ "url": "https://graph.facebook.com/v2.6/" + ...

The issue of banding caused by Bloom and Antialiasing in Three.js rendering

I'm attempting to incorporate a glowing effect into my scene. To achieve this, I understand that using a bloom filter with the EffectComposer is the ideal approach. However, I've encountered an issue where utilizing the EffectComposer compromises ...

Building Dynamic Forms with React.js and Bootstrap for Easy Input Field Management

In the process of developing a web application using React.js and react-bootstrap, I encountered an interesting challenge. On one of the form pages, users should be able to input symptoms of an illness they are dealing with. The key functionality required ...

Using Express Router to serve and display static files in the public directory

The code snippet below is found in my index.js file: var express = require('express'); var app = express(); var PORT = 3000; var routes = require('./scripts/routes/routes'); app.set('views', './views'); app ...

Invalid prop type: A form field received a `checked` prop without a corresponding `onChange` handler

In my project, I have a Parent Component called CandidateList and a Child Component called Candidate. The CandidateList component has a Select All checkbox that triggers a function to set the state when candidates are being selected, and then passes that s ...

Toggle textboxes using jQuery depending on the radio button choice

I'm trying to make specific textboxes appear when a particular radio button is clicked on my form, but I want them to remain hidden otherwise. Here's an example of what I've implemented: HTML: Radio buttons: <p>Show textboxes<inpu ...

Load select box with options upon document load

After the document loads, I want to populate a select box with values from my database using ajax and jQuery. Can someone help me identify what's wrong with my code? <select class="form-control sec" id="sec" name="sec"> <option value="s ...

When utilizing CKEDITOR, the default TEXTAREA is obscured, and CKEDITOR does not appear

I am trying to incorporate CKEDITOR into my project. I have added the ckeditor script in the footer and replaced all instances of it. <script src="<?= site_url('theme/black/assets/plugins/ckeditor/ckeditor.min.js') ?>" type="text/javasc ...

Oops! An unexpected field was encountered while trying to use the uploadMultiple function from dropzone.js

I was looking for a way to allow users to select images to accompany their reviews. That's when I came across dropzone.js. However, I encountered an issue when trying to send multiple images in one request. I expected the req.files to contain an arra ...

Ionic (Angular) experiencing crashes due to numerous HTTP requests being made

My template contains a list of items <ion-list class="ion-text-center"> <div *ngIf="farms$ | async as farmData"> <ion-item (click)="selectFarm(farm)" *ngFor="let farm of farmData" detail=&quo ...

Having trouble with input event listeners in JavaScript?

I've been attempting to trigger the keyup event using EventListener for an input tag, but it doesn't seem to be working and I'm unsure why. Here is the code I have: document.getElementById("ajax").addEventListener("keyup", function() { ...

Tips for creating a responsive background image that adjusts after resizing the window to a certain width

Is there a way to create a responsive background-image that adjusts when the window is resized to a specific width, similar to the main image on ? ...