防止按钮占用其容器的整个宽度

时间:2019-08-21 17:32:07

标签: css reactjs flexbox material-ui styled-components

我在我的应用程序中使用“材质UI”按钮(在样式组件中进行了自定义)。以前,通过将size =“ small”属性传递给按钮,该按钮仅占用按钮文本的宽度,加上我定义的一些填充。即使将其放置在我创建的Flexbox容器中也是如此。但是,当我为该FlexContainer组件定义宽度时,小按钮增加到该容器宽度的100%。

我不想在按钮上定义默认宽度,因为它应该根据按钮文本适当地设置大小。我尝试在按钮本身上设置“ display:inline-flex”,但没有做任何事情。

这是容器组件(较大组件的片段):

       <RightFields flexDirection="column">
          <FieldSpacing>
            <PasswordDisplay />
          </FieldSpacing>
          <FieldSpacing>
            <PaymentDisplay />
          </FieldSpacing>
          <Button pink
            buttonText="Save Changes"
            buttonSize="small"
          />
        </RightFields>


...

const RightFields = styled(FlexContainer)`
  width: 321px;
`

Button.js

const Button = ({buttonText, buttonSize, ...props}) => {

  return (
    <>
      {buttonSize === 'large' ?
        <LargeButton
          variant="contained"
          fullWidth={true}
          size="large"
          {...props}
        >
          {buttonText}
        </LargeButton> :
        <SmallButton
          variant="contained"
          size="small"
          {...props}
        >
          {buttonText}
        </SmallButton>
      }
    </>
  )

}

const StyledButton = styled(MaterialButton)`
  ...
  `

const LargeButton = styled(StyledButton)`
  ...
`

const SmallButton = styled(StyledButton)`
  display: inline-flex;
  flex-grow: 0;
  font-size: 15px;
  font-weight: 500;
  line-height: 18px;
  border-radius: 16px;
  height: 28px;
  min-width: 50px;
  padding: 0 16px;
`

1 个答案:

答案 0 :(得分:1)

尝试使用width: auto;

const SmallButton = styled(StyledButton)`
  display: inline-flex;
  flex-grow: 0;
  font-size: 15px;
  font-weight: 500;
  line-height: 18px;
  border-radius: 16px;
  height: 28px;
  min-width: 50px;
  width: auto;
  padding: 0 16px;
`

这应该只换成文字。