Home > front end >  Make the columns the same width inside Grid React
Make the columns the same width inside Grid React

Time:01-06

I have a grid list like this below, but the problem is that columns have different widths. It is because the lengths of texts inside are different. Can I somehow ignore the text inside and do that the width of the columns is the same?

enter image description here

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

CodePudding user response:

Instead of using auto:

  grid-template-columns: auto auto;

You can solve it by using the fraction unit fr.

A fraction is (in this case) the available width divided by the amount of columns. Then you'll have the same width for each column no matter how long the content is.

Check it out:

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

.item {
  outline: 1px solid black;
}
<div >
  <div >
    Column one.
  </div>
  <div >
    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>

Notice you can also use:

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

CodePudding user response:

Try this:

You can also use from flex instead 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 >
  <div >AAAAAAAAA</div>
  <div >BBB</div>
  <div >CCCCCCC</div>
  <div >D</div>
</div>

  •  Tags:  
  • Related