【问题标题】:I can't align my components horizontally using React and CSS我无法使用 React 和 CSS 水平对齐组件
【发布时间】:2021-12-24 00:05:22
【问题描述】:

我在排列一些 React Bootstrap 卡时遇到了一些问题,我可以将它们水平对齐的唯一方法是将它们都放在一个 div 中,但是如果我以这种方式运行代码,我需要为每张卡使用一个组件,它最终会出错

基本上,每次我添加一张卡片时,它都会垂直对齐,而不是水平对齐。

HostingCard.tsx

import { Card, Button } from "react-bootstrap";
import "./App.css";

export default function HostingCard() {
  return (
      <div className="main">
        <Card style={{ width: "18rem" }}>
          <Card.Img variant="top" src="https://picsum.photos/200" />
          <Card.Body>
            <Card.Title>Card Title</Card.Title>
            <Card.Text>
              Some quick example text to build on the card title and make up the
              bulk of the card's content.
            </Card.Text>
            <Button variant="primary">Go somewhere</Button>
          </Card.Body>
        </Card>
    </div>
  );
}

App.tsx

import React from "react";
import "./App.css";
import Header from "./Header";
import HostingCard from "./HostingCard";

function App() {
  return (
    <div className="App">
      <Header />
      <h1 style={{ padding: "1rem" }}>Hospedagens</h1>
      <HostingCard />
      <HostingCard />
    </div>
  );
}

App.css

 .main {
  display: flex;
  flex-direction: row;
  margin: 0.1rem;
  padding: 1rem;
}

【问题讨论】:

  • 通常你会在你的应用程序组件中构建一个引导网格并循环遍历你的卡片,每个卡片都有一个列。您的标记中不会有一堆单独的组件。

标签: css reactjs react-bootstrap


【解决方案1】:

flexDirection: row 应用于行inside 的子项。您正在创建一列行,其中每一行仅包含一个项目。

要使行作为一行工作,它需要成为卡片的容器,如下所示:

function App() {
  return (
    <div className="App">
      <Header />
      <h1 style={{ padding: "1rem" }}>Hospedagens</h1>
      <div style={{ flexDirection: 'row', /* ...more styles */ }}>
        <HostingCard />
        <HostingCard />
      </div>
    </div>
  );
}

由于您已经在使用 React Bootstrap,您可以浏览它的 Layout 文档并选择他们已经构建的合适的东西,而不是为您自己的 div 设置样式。

Horizontal Stack 看起来像你想要的:

function App() {
  return (
    <div className="App">
      <Header />
      <h1 style={{ padding: "1rem" }}>Hospedagens</h1>
      <Stack direction="horizontal" gap={4}>
        <HostingCard />
        <HostingCard />
      </Stack>
    </div>
  );
}

看看它的实现,你会发现它最终是一个 div 容器,带有 flexDirection: row 以及一堆额外的预设选项和样式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-03
    • 2010-09-07
    • 2019-05-26
    • 1970-01-01
    • 2014-04-11
    • 2021-11-11
    • 2013-09-24
    相关资源
    最近更新 更多