skip to Main Content

I currently have 2 components that I want to be right-aligned with each other. However, I want these 2 components to be in the center of the website. I’ve tried wrapping these 2 components with a div, and setting the margin to 0 auto, but that is not working.

This is the current result: here.
I want to make the 2 components in the center.

<div style={{margin: "0 auto"}}> 
            <Countdown />
            <h3>'til 😴</h3>
        </div>

Countdown and h3 both have textAlign: right.

2

Answers


  1. There are bunch of ways you can make it center; one of the ways you can do it is using flex.

     <div className='App'>
          <div style={{
            display: "flex",
            flexDirection: "column",
            alignItems: "center",
            justifyContent:"right"
           }}> 
              <div>
                <h1 style={{textAlign: "right"}}>Countdown component</h1>
                <h3 style={{textAlign: "right"}}>'til 😴</h3>
              </div>
            </div>
        </div>
    

    Hope it helps 🙂

    Login or Signup to reply.
  2. When you try to center-align elements using the margin: "0 auto" technique, it often requires specifying a fixed width for the container

    <div style={{ width: "50%", margin: "0 auto", textAlign: "right" }}> 
        <Countdown />
        <h3>'til 😴</h3>
    </div>
    

    When attempting to align components using "margin: 0 auto" with a fixed width, you may encounter a limitation in flexibility. Specifically, using a fixed width may not adapt well to varying content sizes or screen dimensions, potentially leading to layout issues or content clipping.

    Considering this challenge, here are two alternative methods to align your components

    1. Using Flex Layout

    Flexbox provides a flexible solution, allowing you to center the container while keeping the content right-aligned.

    <div style={{ display: "flex", justifyContent: "center" }}>
        <div style={{ textAlign: "right" }}>
            <Countdown />
            <h3>'til 😴</h3>
        </div>
    </div>
    

    2. Using CSS Grid

    You can create a similar alignment using CSS Grid. With grid layout, you can easily center the content while maintaining the right alignment.

    <div style={{ display: "grid", justifyContent: "center" }}>
        <div style={{ textAlign: "right" }}>
            <Countdown />
            <h3>'til 😴</h3>
        </div>
    </div>
    

    Both of these methods should provide a more flexible and responsive solution for aligning the components as described. For a deeper understanding of Flexbox and CSS Grid alignment, you might find this guide helpful: CSS Grid & Flexbox Component Alignment Guide.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search