【问题标题】:Centering grid items in auto rows [duplicate]在自动行中居中网格项目[重复]
【发布时间】:2020-07-16 10:50:24
【问题描述】:

我正在使用 CSS 网格制作日历,我很好奇如果没有明确定义该行,是否可以将推送到下一行的网格项居中。

下面是代码示例:

#calendar {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(100px, 150px));
  /* grid-template-rows: repeat(auto-fit, 1fr); */
  justify-content: center;
  min-height: 10vh;
  max-height: 100vh;
  width: 100%;
  padding: 1rem;
}

#calendar>div {
  height: 100px;
  width: 100%;
  border: 2px solid black;
}
<div id="calendar">

  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
  <div></div>
</div>

【问题讨论】:

    标签: css


    【解决方案1】:

    您可能需要使用某种弹性处理程序。请试试这个。并满足您的需求。

    html

    #calendar {
      display: flex;
      flex-wrap: wrap;
      justify-content: center;
    }
    
    #calendar > div {
      flex: 0 0 calc(16.66% - 20px);
      background: teal;
      color: white;
      padding: 20px;
      margin: 10px;
    }
    
    * {
      box-sizing: border-box;
    }
    

    HTML

    <div id="calendar">
      <div>Item</div>
      <div>Item</div>
      <div>Item</div>
      <div>Item</div>
      <div>Item</div>
      <div>Item</div>
      <div>Item</div>
      <div>Item</div>
      <div>Item</div>
      <div>Item</div>
      <div>Item</div>
    </div>
    

    【讨论】:

      【解决方案2】:

      最好使用 flex 而不是 grid。

      #calendar {
        min-height: 10vh;
        max-height: 100vh;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      
      #calendar>div {
        height: 100px;  
          text-align: center;
          flex: 1 0 auto;
        border: 2px solid black;
      }
      <div id="calendar">
      
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
        <div></div>
      </div>

      【讨论】:

        猜你喜欢
        • 2018-09-05
        • 1970-01-01
        • 1970-01-01
        • 2018-11-24
        • 2019-10-10
        • 1970-01-01
        • 2020-06-18
        • 2022-07-29
        • 1970-01-01
        相关资源
        最近更新 更多