some nooby questions
some nooby questions

Reputation: 693

Make the columns the same width inside Grid React

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

Upvotes: 1

Views: 1812

Answers (2)

Arman Ebrahimi
Arman Ebrahimi

Reputation: 2317

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>

Upvotes: 0

Leo
Leo

Reputation: 947

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

Upvotes: 2

Related Questions