1

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;
`;
1
  • Can you include a codesandbox so that we can check by running? Commented Jan 6, 2022 at 10:10

2 Answers 2

2

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

Notice you can also use:

  grid-template-columns: repeat(2, 1fr);
Sign up to request clarification or add additional context in comments.

Comments

0

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 class="container">
  <div class="item">AAAAAAAAA</div>
  <div class="item">BBB</div>
  <div class="item">CCCCCCC</div>
  <div class="item">D</div>
</div>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.