I'm having some problems lining up some React Bootstrap cards, the only way I could align them horizontally was by putting them both inside a div, but I need a component for each card, if I ran the code that way, it would end up going wrong
Basically, every time I add a card, it's aligned vertically, not horizontally.
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;
}
CodePudding user response:
flexDirection: row
applies to the children inside the row. You're creating a column of rows where each row contains only one item in each.
For the row to work as a row it needs to be a container for the cards, something like this:
function App() {
return (
<div className="App">
<Header />
<h1 style={{ padding: "1rem" }}>Hospedagens</h1>
<div style={{ flexDirection: 'row', /* ...more styles */ }}>
<HostingCard />
<HostingCard />
</div>
</div>
);
}
Since you're already using React Bootstrap, you can browse its Layout docs and choose something suitable that they already built instead of styling your own div.
Horizontal Stack looks like what you want:
function App() {
return (
<div className="App">
<Header />
<h1 style={{ padding: "1rem" }}>Hospedagens</h1>
<Stack direction="horizontal" gap={4}>
<HostingCard />
<HostingCard />
</Stack>
</div>
);
}
Look at its implementation and you'll see it's ultimately a div
container with flexDirection: row
plus a bunch of additional preset options and styles.