Search code examples
htmlcsscss-grid

How can I make the content of a grid element not affect its size?


Basically i just want the four boxes in the snippet below to be the same size while still having the text centered inside the first box. Right now the text 'qwe' affects the size of the first box. Also it has to be using display: grid, like it is now.

.asd {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  display: grid;
  grid-template-columns: repeat(4 1fr);
  grid-template-rows: repeat(4 1fr);
}

.asd > div {
  border: 1px solid black;
  display: flex;
  justify-content: center;
  align-items: center;
}

.box1 {
  grid-column: 1/2;
  grid-row: 1/2;
}

.box4 {
    grid-column: 2/3;
  grid-row: 2/3;
}
<div class="asd">
  <div class="box1">qwe</div>
  <div class="box2"></div>
  <div class="box3"></div>
  <div class="box4"></div>
</div>


Solution

  • Your css is invalid grid-template-columns: repeat(4 1fr);grid-template-rows: repeat(4 1fr);

    use

    grid-template-columns: 1fr 1fr; grid-template-rows: 1fr 1fr;

    If the text grow out of the box use overflow: hidden;

    .asd {
      width: 100px;
      height: 100px;
      border: 1px solid black;
      display: grid;
    grid-template-columns: 1fr 1fr;
    grid-template-rows: 1fr 1fr;
    }
    
    .asd > div {
      border: 1px solid black;
      display: flex;
      justify-content: center;
      align-items: center;
    overflow: hidden;
    }
    <div class="asd">
      <div class="box1">qwe qwe qwe</div>
      <div class="box2"></div>
      <div class="box3"></div>
      <div class="box4"></div>
    </div>