[英]How to put content center vertically and horizontally with tailwind.css in React, Next.js?
我正在嘗試在 React,Next.js 項目中使用 tailwind.css 將 svg 組件垂直和水平放置在父 div 元素的中心。 請讓我知道我的代碼哪里有問題。
對於下面粘貼的 png 中顯示的當前結果,svg 圖標不在其父 div 元素的中心。 此外,父 div 與該行的同級 div 元素的高度不同。 我想解決這兩個問題。 在我按照 Mr.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>
)
}
//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;
}
要使所有子項水平居中,您可以在最上面的<div>
上添加place-items-center
,然后將 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>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.