如何在 React、Next.js 中使用 tailwind.css 垂直和水平放置内容中心?

ska*_*ori 2 css svg reactjs next.js tailwind-css

我试图在 React、Next.js 项目中使用 tailwind.css 将 svg 组件垂直和水平地放置在父 div 元素的中心。请让我知道我的代码哪里有问题。

对于下面粘贴的 png 中显示的当前结果,svg 图标不在其父 div 元素的中心。此外,父 div 与该行的同级 div 元素的高度不同。我想解决这两个问题。在我遵循 Juliomalves 先生的回答后,第二个粘贴的 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>
  );
}
Run Code Online (Sandbox Code Playgroud)
//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>
  );
}
Run Code Online (Sandbox Code Playgroud)
//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>
  );
}
Run Code Online (Sandbox Code Playgroud)
//svg.module.css

.svg-char {
   display: inline-block; 
   @apply border-2;
}
Run Code Online (Sandbox Code Playgroud)

jul*_*ves 6

要使所有子项水平居中,您可以添加place-items-center最顶部的<div>,然后将 SVG 在其父容器中居中,只需将flex和应用于place-content-center容器即可。

<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>
Run Code Online (Sandbox Code Playgroud)