Achieving vertical and horizontal centering of content using tailwind.css in React with Next.js

Struggling to align an svg component at the center of a parent div element both vertically and horizontally using tailwind.css in a React project. Seeking feedback on my code below to identify any mistakes.

The current issue, as shown in the included png image, is that the svg icon is not centered within its parent div. Additionally, the parent div does not match the height of its sibling div elements in the row. Looking to address these two issues.

To visualize the improvement, refer to the second png image which showcases the desired outcome after implementing suggestions from Mr. Juliomalves.

https://i.sstatic.net/pao59.png https://i.sstatic.net/UOuPm.png

//index.js

import { RedToBlueCols } from "../components/cols";

export default function Home() {
  return (
    <RedToBlueCols width="120" height="60">
      <div>
        <p>red</p>
        <p>red</p>
        <p>red</p>
        <p>red</p>
        <p>red</p>
      </div>
      <div>
        <p>blue</p>
        <p>blue</p>
        <p>blue</p>
        <p>blue</p>
        <p>blue</p>
      </div>
    </RedToBlueCols>
  );
}
//cols.js

import { RedToBlue } from "./mysvg";

export function RedToBlueCols(props) {
  return (
    <div className="w-screen flex flex-wrap flex-row ">
      <div className="w-2/12 "></div>
      <div className="w-3/12 border-4">{props.children[0]}</div>
      <div className="w-2/12 border-4 content-center h-full ">
        <RedToBlue width="120" height="48"></RedToBlue>
      </div>
      <div className="w-3/12 border-4">{props.children[1]}</div>
      <div className="w-2/12"></div>
    </div>
  );
}
//mysvg.js

import styles from "../styles/svg.module.css";
export function RedToBlue(props) {
  const { height, width } = props;
  return (
    <span class={styles["svg-char"]}>
      <svg
        width={width}
        height={height}
        viewBox="0 0 30 6"
        xmlns="http://www.w3.org/2000/svg"
        {...props}
      >
        <title>RedToBlue</title>
        <defs>
          <linearGradient
            id="gradRtoB"
            x1="0"
            y1="6"
            x2="30"
            y2="6"
            gradientUnits="userSpaceOnUse"
            spreadMethod="repeat"
          >
            <stop offset="30%" stopColor="#ff0000" stopOpacity="1" />
            <stop offset="50%" stopColor="#ffff00" stopOpacity="1" />
            <stop offset="70%" stopColor="#0000ff" stopOpacity="1" />
          </linearGradient>
        </defs>
        <g fill="white">
          <path
            d="M0,0 l 5,3 l -5,3 h 25 l 5,-3 l -5,-3 z"
            fill="url(#gradRtoB)"
          />
        </g>
      </svg>
    </span>
  );
}
//svg.module.css

.svg-char {
   display: inline-block; 
   @apply border-2;
}

Answer №1

To horizontally center all child elements, you can include place-items-center on the highest level <div>, and then to center the SVG within its parent container, simply add flex and place-content-center to the container.

<div className="w-screen flex flex-wrap flex-row place-items-center">
    <!-- -->
    <div className="flex place-content-center w-2/12 border-4 h-full"><!-- SVG container -->
        <!-- -->
    </div>
    <!-- -->
</div>

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

Error 504: GATEWAY_TIMEOUT - Vercel hosting running NextJS

I've encountered a frustrating issue with Vercel and NextJS that's causing me some headaches. My NextJS application has simple api routes, but when I try to access my hello world endpoint (or any other endpoint), I'm faced with the following ...

When resizing the browser, HTML/CSS elements tend to shift positions :(

I've experimented with different position values like absolute, fixed, and static without success. Wrapping the element in a div didn't yield the desired result, so I'm seeking assistance to correct this. (If that is the solution) The issu ...

Encountering a Laravel React issue with Error 500 during authentication process

I've been grappling with this issue for a few days now, but I just can't seem to crack it. Can anyone lend me a hand? Here is the code snippet for the Laravel UserController: public function login(Request $request){ $request->validate( ...

Guide to creating a responsive layout using CSS and HTML

I am looking to position the main contents (content 1 and content 2) in between two side menus on my exercise page. At the moment, the main contents are overlapping with the two menus. Can someone guide me on how to fix this alignment issue? Thank you. ...

Is there a way to change the background color of the body on click and have it applied throughout the entire site

Is there a way to change the background-color of the entire site and specific modal elements when a user switches between two radio buttons? Here is the HTML code for the radio buttons: <div class="btn-group btn-group-xs" data-toggle="buttons"> ...

The text content is not in alignment with the server-rendered HTML for translation purposes with i18n

I have successfully implemented i18n in my Next.js project. The folder structure for my locales is as follows: public/locales/en/translation.json and public/locales/fr/translation.json The error I am encountering is: Uncaught Error: Text content does n ...

Is there a way to alter the background color of a Material UI card when it is being hovered over

I'm currently using material ui with react and I have a question regarding the background color of my card component when a user hovers over it. Can someone help me figure out how to achieve this? For reference, here is the live code link in CodeSand ...

Having trouble with the CSS `not` selector?

Below is the code snippet I experimented with XHTML <div> <span>Span1</span> <span>Span12</span> <span>Span13</span> </div> <div> <span>Span1</span> <span> ...

What is the best way to apply the default MUI5 theme and customize the styling of individual components in MUI5?

import { styled } from "@mui/system"; import { CardTravel, Home, People } from "@mui/icons-material"; import { Box, Container, Typography } from "@mui/material"; import React from "react"; const BoxContainer = style ...

Field input displacement

I am experiencing an issue with my contact form, specifically with the message subject field displayed as a menu. The problem only seems to occur on wide desktop displays, where it appears offset from the rest of the form. Despite my efforts to troublesho ...

Resize the Bootstrap select element based on its contents

My HTML code includes a <select> element that is styled using Bootstrap 5. <div class="col-md-12"> <div class="mb-3"> <label asp-for="Schedule.Minutes" class="control-label"></l ...

Is it possible to apply styles to the body of a document using styled-components?

Is it possible to apply styles from styled-components to a parent element, such as the <body> tag, in a way that resembles the following: const PageWrapper = styled.div` body { font-size: 62.5%; } ` ...

Is the z-index useless when the button is positioned behind divs and other elements?

I would like the "Kontakt" button to appear in the top right corner of the page, always on top of everything else. I have tried setting the z-index to z-index: 99999999999 !important;, but it doesn't seem to be working... On desktop, the button displ ...

Utilizing TailwindCSS and React for dynamic class manipulation

In my code, there is a functionality that detects form errors and adds a div element if an error occurs: {touched && normalizedError && ( <div className="visible alert-error text-xs text-red-500" role="alert"> ...

The npm postinstall script will only execute if no packages are currently being installed

I made a mistake The reason behind why running npm install whatever results in the deletion of the node_modules/- folder is not what I initially thought. I mistakenly believed it executed the preinstall script but skipped the postinstall script, which was ...

Securing server actions with Next Auth in the latest version of Next JS 14

My journey with building my first Next JS 14 App integrated with App Router v4 for authentication and authorization has been quite rewarding. Everything was working perfectly until I hit a roadblock with Server Actions, which are meant to enhance the effi ...

Error in display of file names on Chrome DevTools

Currently working on a project with ReactJS and encountering an issue with the file names displayed in Google Chrome DevTools. The project was initialized with create-react-app. Instead of main.chunk.js, I would prefer to see src/Index.jsx in the consol ...

@vx/enhanced responsiveness with TypeScript

I am currently utilizing the @vx/responsive library in an attempt to retrieve the width of a parent component. Below are snippets from my code: import * as React from 'react' import { inject, observer } from 'mobx-react' import { IGlob ...

Issues with routing on Zeit Now platform are causing a 404 NOT FOUND error when attempting to reload pages that are not the

Recently, I purchased a Next.js template from Themeforest and attempted to deploy it to Zeit Now. This particular project is set up as a monorepo using Lerna and Yarn workspace. The code for the Next.js app can be found inside the packages/landing folder. ...

How to change the image source using jQuery when hovering over a div and set its class to active?

I am working with a div structure that looks like this: <div class="row margin-bottom-20"> <div class="col-md-3 service-box-v1" id="div1"> <div><a href="#"><img src="path" id="img1" /></a></div> ...