Search code examples
reactjsstylesstyled-components

How to center buttons with styled-components?


Can't figure out how to center 2 buttons horizontally with styled-components.

Below is my code. Tried many ways to center, but didn't work.

import React from "react"
import styled from "styled-components"

const HomeStyles = styled.div`
  h1 {
    font-size: 1.5em;
    text-align: center;
    color: royalblue;
  }

  button {
    font-size: 1em;
    margin: 1em;
    padding: 0.25em 1em;
    border: 2px solid royalblue;
    border-radius: 3px;
    color: royalblue;
  }
`

export default function Home() {
  return (
    <HomeStyles>
      <h1>Title</h1>
      <button>Button1</button>
      <button>Button2</button>
    </HomeStyles>
  )
}

UPDATE: I need to center buttons horizontally

enter image description here


Solution

  • Have you tried using flexbox on parent element?

    
    const HomeStyles = styled.div`
      display: flex;
      flex-direction: column;
      justify-items: center;
      align-items: center;
      ....
    `;
    
    const ButtonsWrapper = styled.div`
      display: flex;
      justify-items: center;
      align-items: center;
    `;
    
        <HomeStyles>
          <h1>Title</h1>
          <ButtonsWrapper>
            <button>Button1</button>
            <button>Button2</button>
          </ButtonsWrapper>
        </HomeStyles>
    

    Edit Q-64852902-flexbox