Search code examples
javascriptcssnode.jsreactjsantd

How to fix the antd card position?


I want my antd card to be displayed in the center. When I click a button, this card needs to be displayed and it also needs to aligned in the centre. I have written the code to make it work like that but soon after I click the button, the card first gets displayed on the left and then comes to the center. How do I avoid this? I want the card to be displayed in the center directly on a button click.

const [show, setShow] = useState(false);


<div>
<Button onClick={() => setShow(true)}>Hi</Button>
{show ? (

  <Col style={{ height: "750px", width: "100%" }}>
    <Card className="cardStyle">
      <p>Card title will come here!!!</p>
    </Card>
  </Col>
) : null}
</div>

Css:

.cardStyle {
flex-direction: row;
justify-content: center;
align-items: center;
width: 300px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}

Is if because of existing css for other components?


Solution

  • You just need to apply some styling to your column to center it and its contents. Using transform and top/left positioning isn't going to be all that consistent here.

    Here's a codepen showing your code, but I've moved the styling for the column in to css and added flex position:

    .colStyle {
      height: 750px; 
      display: flex;
      justify-content: center;
      align-items: center;
    }
    
    .cardStyle {
      flex-direction: row;
      justify-content: center;
      align-items: center;
      width: 300px;
    }