【问题标题】:Make the columns the same width inside Grid React在 Grid React 中使列的宽度相同
【发布时间】:2022-01-06 09:55:36
【问题描述】:

我有一个像下面这样的网格列表,但问题是列有不同的widths。这是因为里面的文本长度不同。我能以某种方式忽略里面的文字,让列的宽度相同吗?

<Container>
    {elements.map((e, i) => (
        <StyledLabel key={i}>
        <StyledInput
            type="radio"
        />
        <Option>{e.text}</Option>
        </StyledLabel>
    ))}
</Container>
const Option = styled.span`
  display: flex;
  border: 1px solid grey;
  height: 30px;
  font-size: 14px;
  cursor: pointer;
  color: grey;
  align-items: center;
  justify-content: center;
  box-sizing: border-box;
  overflow: hidden;
  text-transform: uppercase;
  width: 1fr;
`;

const StyledLabel = styled.label`
  cursor: pointer;
`;

const StyledInput = styled.input`
  display: none;
`;

const Container = styled.div`
  width: 300px;
  display: grid;
  grid-gap: 5px;
  grid-template-columns: auto auto;
`;

【问题讨论】:

  • 能否包含一个代码框,以便我们通过运行进行检查?

标签: javascript html css reactjs grid


【解决方案1】:

而不是使用auto:

  grid-template-columns: auto auto;

您可以使用分数单元fr来解决它。

分数是(在这种情况下)可用宽度除以列数。然后,无论内容有多长,每列的宽度都将相同。

检查一下:

.container {
  display: grid;
  grid-template-columns: 1fr 1fr;
}

.item {
  outline: 1px solid black;
}
<div class="container">
  <div class="item">
    Column one.
  </div>
  <div class="item">
    A second column with more text than the first one. A second column with more text than the first one. A second column with more text than the first one.
  </div>
</div>

注意你也可以使用:

  grid-template-columns: repeat(2, 1fr);

【讨论】:

    【解决方案2】:

    试试这个:

    你也可以用 from flex 代替 grid:

    .container {
      display: flex;
      border: solid green;
      justify-content: space-between;
    }
    
    .item{
      box-sizing: border-box;
      text-align: center;
      padding:5px;
      background-color: red;
      width: 20%;/* instead 25%,because to be made the gap. */
      border: solid;
    }
    <div class="container">
      <div class="item">AAAAAAAAA</div>
      <div class="item">BBB</div>
      <div class="item">CCCCCCC</div>
      <div class="item">D</div>
    </div>

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-24
      • 1970-01-01
      • 2011-06-29
      • 2021-05-03
      • 1970-01-01
      • 2020-12-04
      相关资源
      最近更新 更多