【问题标题】:How to center buttons with styled-components?如何使用样式组件使按钮居中?
【发布时间】:2021-02-27 08:23:28
【问题描述】:

无法弄清楚如何使用styled-components 将 2 个按钮水平居中。

下面是我的代码。 尝试了很多方法居中,但没有奏效。

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>
  )
}

更新:我需要将按钮水平居中

【问题讨论】:

    标签: reactjs styles styled-components


    【解决方案1】:

    您是否尝试过在父元素上使用flexbox

    
    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>
    

    【讨论】:

    • 谢谢,但它是垂直放置按钮。我希望按钮保持水平。
    • 所以用flex-direction 行包裹你的按钮
    猜你喜欢
    • 2021-09-06
    • 1970-01-01
    • 2013-09-13
    • 2015-12-06
    • 2021-07-03
    • 1970-01-01
    • 1970-01-01
    • 2019-09-11
    • 2018-02-08
    相关资源
    最近更新 更多