Search code examples
htmlcssflexboxstyled-components

Flexbox styles not working in React Styled Component


I've been struggling with the styling of my React app using StyledComponents, however I've succesfully re-created & fixed the issue in this codepen:

https://codepen.io/simoncunningham/pen/mdwMgyL

(Basically using flex: 1) to ensure the checkbox expands to the full width of parent) however I cannot reflect this change with my StyledComponents, can anyone see where I might be missing something?

const StyledWrapper = styled.div`
  position: relative;
  display: inline-flex;
  min-height: 1.5rem;
  margin-right: 1rem;
  padding: 0.5rem
  width: 200px;
`;

const StyledHiddenInput = styled.input`
  position: absolute;
  z-index: -1;
  visibility: hidden;

  &[type="checkbox"]:checked ~ label::after {
    background-image: url("${checkboxImage}");
    width: 20px;
    height: 20px;
  }
`;

const StyledLabel = styled.label`
  position: relative;
  margin-bottom: 0;
  display: flex;
  margin-left: 0;
  margin-right: 24px;
  flex-direction: row-reverse;
  justify-content: space-between;
  flex: 1;

  &::before {
    display: block;
    top: 4px;
    width: 20px;
    height: 20px;
    content: "";
    background-color: #fff;
    border: 1px solid black;
    border-radius: 4px;
  }

  &::after {
    position: absolute;
    display: block;
    top: 4px;
    height: 20px;
    content: "";
    background-repeat: no-repeat;
    background-position: center center;
    background-size: 80%;
  }
`;

const StyledLabelWrapper = styled.div`
  margin-left: 24px;
  margin-right: 0;
`;
<StyledWrapper>
   <StyledHiddenInput />
   <StyledLabel>
      <StyledLabelWrapper>{label}</StyledLabelWrapper>
   </StyledLabel>
</StyledWrapper>

Screenshot of output from Codepen (working as expected with checkbox displaying as far right as possible)::

enter image description here

Screenshot of output from Styled Component:

enter image description here


Solution

  • Solved the issue by updating the width on StyledWrapper like so:

    const StyledWrapper = styled.div`
      display: inline-flex;
      min-height: 1.5rem;
      padding: 0.5rem
      width: 100%;
    `;
    
    

    which allowed the content to grow to the full width of its container.