在 Grid React 中使列的宽度相同

Make the columns the same width inside Grid React

我有一个像下面这样的网格列表,但问题是列有不同的 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;
`;

而不是使用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);

试试这个:

您也可以使用 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>