首页 > 解决方案 > Prevent button from taking up the full width of its container

问题描述

I am using the Material UI button (with customizations in styled-components) in my app. Previously, by passing the size="small" prop to the button, the button was only taking up the width of the button text, plus some padding that I defined. It was doing so even when placed within a Flexbox container I created. However, when I defined a width for that FlexContainer component, the small button increased to 100% of the width of that container.

I don't want to define a default width on the button because it should appropriately size based on the button text. I tried setting "display: inline-flex" on the button itself, but that did not do anything.

Here is the container component (fragment of larger component):

       <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;
`

标签: cssreactjsflexboxmaterial-uistyled-components

解决方案


Try using 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;
`

This should wrap to the text only.


推荐阅读