css - nested div in grid does not respect grid sizes

自作多情 提交于 2019-12-13 03:47:10

问题


So I'm trying to display cards within a grid. I would like the card size to be based on the grid size and then to overlay text on top of it that correctly matches the width.

Here's my implementation so far but it seems like the div/img no longer respects the grid's sizes

for (let i = 0; i < 15; i++)
{
  $("#grid").append(`
    <div class="item">
    	<div>
        <img src="http://via.placeholder.com/250x350" />
        <div class="text">
          sadfsd
        </div>
			</div>
    </div>
  `);  
}
.flex {
  border: 1px solid black;
  display: flex;
  flex-direction: column;
  height: 100vh;
}
.footer {
  height: 20%;
}
.upper {
  flex: 1;
  overflow: auto;
}

#grid {
  border: 1px solid black;
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  height: 100%;
  position: relative;
  max-width: 100%;
  box-sizing: border-box;
}

.item {
  display: inline-block;               
  text-align: center;                    
  position: relative;
}

.inner {
  border: 1px solid red;
  max-height: 100%;
  max-width: 100%;

  
}

.text {
  position: absolute;
  bottom: 10%;
  left: 50%;
  transform: translateX(-50%);
  height: 30%;
  border: 1px solid black;
  width: 90%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="flex">
  <div class='upper'>
    <div id="grid">
    </div>  
  </div>
  <div class="footer">
    footer
  </div>
</div>

What I want is it to look something like this (of course with the text matching the width of the image)

for (let i = 0; i < 15; i++)
{
  $("#grid").append(`
    <div class="item">
      <img src="http://via.placeholder.com/150x350" />
      <div class="text">
        text
      </div>
    </div>
  `);  
}
.flex {
  border: 1px solid black;
  display: flex;
  flex-direction: column;
  height: 100vh;
}
.footer {
  height: 20%;
}
.upper {
  flex: 1;
  overflow: auto;
}

#grid {
  border: 1px solid black;
  display: grid;
  grid-template-columns: 1fr 1fr 1fr 1fr 1fr;
  grid-template-rows: 1fr 1fr 1fr;
  height: 100%;
  position: relative;
  max-width: 100%;
  box-sizing: border-box;                  /*  added  */
}

.item {
  position: relative;
}

.text {
  border: 1px solid black;
  position: absolute;
  bottom: 10%;
  left: 50%;
  transform: translateX(-50%);
  width: 90%;
  height: 30%;
}

img {
  display: block;                         
  margin: 0 auto;                         
  max-height: 100%;
  max-width: 100%;           
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div class="flex">
  <div class='upper'>
    <div id="grid">
    </div>  
  </div>
  <div class="footer">
    footer
  </div>
</div>

来源:https://stackoverflow.com/questions/47255747/css-nested-div-in-grid-does-not-respect-grid-sizes

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!