【问题标题】:Flexbox styles not working in React Styled ComponentFlexbox 样式在 React Styled 组件中不起作用
【发布时间】:2022-01-01 05:41:21
【问题描述】:

我一直在努力使用 StyledComponents 为我的 React 应用程序设计样式,但是我已经成功地在这个 codepen 中重新创建并修复了这个问题:

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

(基本上使用flex: 1)来确保复选框扩展到父级的整个宽度)但是我无法用我的StyledComponents反映这种变化,任何人都可以看到我可能遗漏了什么吗?

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>

Codepen 输出的屏幕截图(按预期工作,复选框显示在尽可能右侧)::

样式化组件的输出截图:

【问题讨论】:

    标签: html css flexbox styled-components


    【解决方案1】:

    通过更新 StyledWrapper 上的 width 解决了这个问题,如下所示:

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

    这允许内容增长到其容器的整个宽度。

    【讨论】:

      【解决方案2】:

      试试这个(添加的最后 2 个属性):

      .label::before {
        display: block;
        width: 20px;
        height: 20px;
        content: "";
        background-color: #fff;
        border: 1px solid black;
        border-radius: 4px;
        position: relative;
        right: 0;
      }
      

      【讨论】:

      • 请考虑添加 lang-CSS 以获得正确的语法。
      猜你喜欢
      • 1970-01-01
      • 2020-11-03
      • 2020-06-09
      • 2020-05-11
      • 2018-11-22
      • 2021-11-04
      • 1970-01-01
      • 1970-01-01
      • 2018-12-14
      相关资源
      最近更新 更多