【问题标题】:Flexbox - how to align items vertically with flex-col?Flexbox - 如何使用 flex-col 垂直对齐项目?
【发布时间】:2021-10-29 15:01:36
【问题描述】:
const Product = ({product}) => {
    return (
        <div className="rounded shadow flex-col justify-center overflow-hidden">
            <img className="" src={product.image} />
            <span className="block h-16">{product.name}</span>
            <span className="block">{product.price}</span>
            <button className="px-4 py-2 my-2 bg-green-200 rounded block">Add to Cart</button>
        </div>
    )
}

这是 React 中使用 Tailwind CSS 的卡片组件。 我无法让项目在卡片中居中。

我使用了 flex-col,所以现在方向是垂直的,并尝试了 justify-center 和 items-center with tailwind,但它似乎没有移动任何东西。

如果您使用 flex-col,轴不会被交换,因此您需要使用 align-items: center 使其垂直居中?

【问题讨论】:

    标签: reactjs flexbox tailwind-css


    【解决方案1】:

    justify-content CSS 属性在当前flex-direction 轴上对齐,而align-items CSS 属性在垂直于当前flex-direction 的轴上对齐。

    因此,如果容器将 flex-direction 设置为 column (.flex-col),则需要使用 .items-center(在 CSS 中:align-items: center)将其子级水平居中。

    但是,如果居中的子元素是块级的,即使元素(作为 100% 宽度的框)居中,它的文本仍可能是左对齐的在列中,在这种情况下,您需要在子级上使用 text-align: center (.text-center) 以水平对齐其内容。

    关于 flexbox 的深入文章,我推荐A complete guide to flexbox。

    【讨论】:

    • 感谢您的澄清,这是有道理的。
    猜你喜欢
    • 2017-09-30
    • 2018-07-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-06
    • 2022-01-26
    • 2017-07-18
    相关资源
    最近更新 更多