首页 > 解决方案 > CSS网格拉伸行内容以适应父容器

问题描述

有没有办法让网格项目拉伸父容器的长度?我终其一生都无法弄清楚。

基本上我试图用网格构建一个日历,因为 idk 这似乎是最好的选择。我得到了 7 列,它们拉伸了父容器的宽度。但是,网格行没有。我已经尝试了来自 SO 和其他地方的大量潜在解决方案,但它们似乎都不起作用。

设置days height:100%;会导致它在页面下方延伸太远并溢出,这是不可取的。如果我把它拿出来,那么他们就不会填满空间而只是聚在一起。理想情况下,我想要 7 x 5 的方形盒子,但此时我将采用均匀间隔的矩形。我在做什么错或误解?

这是一个片段:(css是scss)


.main-container {
  display: flex;
  width: 100%;
  height: 100%;
}

.calendar {
  background-color: transparent;
  width: 100%;
  height: 100%;
  //remove italics is for testing. delete after done
  font-style: normal;
  position: relative;
}


.month {
  padding: 7rem 10rem;
  width: 100%;
  background: #eee;
  text-align: center;
}

.month ul {
  display: flex;
  justify-content: space-between;
  list-style: none;

  & a{
    color: #222;
    text-decoration: none;
  }
  
}

// use grid 7 x 5 (modify for february in js)
.weekdays {
  background: #222;
  color: #eee
  display: grid;
  grid-template-columns: repeat(7,1fr);
  list-style: none;
  text-align: center;
  font-weight: bold;
}


.days {
  list-style: none;
  text-align: center;
  font-weight: 200;
  text-decoration: none;

  background: #eee;

  display: grid;
  grid-template: repeat(5,1fr) / repeat(7,1fr); // rows / columns
  justify-content: stretch;
  
  width: 100%;
  height: 100%;
  position: absolute;
  
  & > li {
    background: #www;
    height: 100%;
  }
}
 <div class="main-container">
  <div class="calendar">
    <div class="month">
        <ul>
            <li class="prev"><a href="#" class="month__prev">&#10094</a></li>
            <li>August<br><span style="font-size:18px">2020</span></li>
            <li class="next"><a href="#" class="month__prev">&#10095</a></li>
        </ul>
    </div>
    <ul class="weekdays">
        <li>Monday</li>
        <li>Tuesday</li>
        <li>Wednesday</li>
        <li>Thursday</li>
        <li>Friday</li>
        <li>Saturday</li>
        <li>Sunday</li>
    </ul>
    <ul class="days">
        <li><a href="#" class="day">1</a></li>
        <li><a href="#" class="day">2</a></li>
        <li><a href="#" class="day"> 3</a></li>
        <li><a href="#" class="day"> 4</a></li>
        ...
<!--and so on-->

逻辑是:将所有网格容器包装在一个flex项目中,因为flex它是“布局”并且grid是组织。

标签: htmlcsscss-grid

解决方案


我想出了一个可行的解决方案。我添加了一个display:flex并将其设置为父元素中的列,但我忘记了在哪里,因为我只是在反复试验很多事情。我认为这是calendar元素,因为它不在 OP 中。它给了我这个输出,这是我正在寻找的(对不起颜色)。

在此处输入图像描述


推荐阅读