Home > Software design >  How do I make my parent div resize with my child div using display: grid and flex?
How do I make my parent div resize with my child div using display: grid and flex?

Time:03-08

html, body {
  height: 100vh;
  width: 100%;
  margin: 0;
  padding: 0;
}

* {
  box-sizing: border-box;
}

.container {
  display: grid;
  grid-template-columns: repeat(5, calc(20% - 20px));
  grid-auto-rows: 1fr;
  grid-gap: 20px;
  margin-left: 20px;
}

.container .item {
  background-color: red;
}

.item .inside {
  display: flex;
  justify-content: space-between;
}

.inside-elem {
  padding: 20px;
}
  <div >
    <div >
    
      <div >
        <span >ABC</span>
        <span >EFG</span>
      </div>
    </div>
    
    <div >
    
    </div>
    
    <div >
    
    </div>
    
    <div >
    
    </div>
    
    <div >
    
    </div>
  </div>
  

In the example above, if you zoom in, you could see that EFG goes outside the grid cell. I want the grid cell to resize with its child element while maintaining the given format. The issue stems from me adding padding: 20px, the grid cell doesn't resize on the padding.

I tried adding border-box but that didn't fix it.

CodePudding user response:

Is this what you're looking for? I changed your .container to display: flex. It maintains the layout and expands to fit the content.

I also added width: 100%; to the .item rule so that it takes up the full available width.

html, body {
  height: 100vh;
  width: 100%;
  margin: 0;
  padding: 0;
}

* {
  box-sizing: border-box;
}

.container {
  display: flex;
  gap: 20px;
  justify-content: space-evenly
}

.container .item {
  background-color: red;
  width: 100%;
}

.item .inside {
  display: flex;
  justify-content: space-between;
}

.inside-elem {
  padding: 20px;
}
  <div >
    <div >
    
      <div >
        <span >ABC</span>
        <span >EFG</span>
      </div>
    </div>
    
    <div >
    
    </div>
    
    <div >
    
    </div>
    
    <div >
    
    </div>
    
    <div >
    
    </div>
  </div>
  

  •  Tags:  
  • css
  • Related