为什么我的CSS网格布局div不以大视口为中心?

时间:2019-10-09 10:42:10

标签: html css css-grid

我正在尝试在父div内显示div,但希望子div位于中间而不是从父div的开头开始。下面提供了HTML / CSS,以及在iPad(看起来不错)和计算机(不是我想要的东西)上的屏幕截图。

.inner-tile {
  display: inline-grid;
  grid-gap: 5px;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr ));
  grid-template-rows: 1fr;
  justify-items: center;

  width: 100%;
  height: auto;
  font-size: 18px;
  padding-bottom: 10px;
}

.event {
  border: 1px solid grey;
  border-radius: 4px;
  min-width: 240px;
  min-height: 270px;
  width: 90%;
  height: auto;
}
  <div class = "inner-tile">
    <div class = "event">
      <div class="event-image"></div>
      <a href = "#learnmore" class = "learn-more">event</a>
    </div>          
    <div class = "event">
      <div class="event-image"></div>
      <a href = "#learnmore" class = "learn-more">event</a>
    </div>          
    <div class = "event">
      <div class="event-image"></div>
      <a href = "#learnmore" class = "learn-more">event</a>
    </div>          
    <div class = "event">
      <div class="event-image"></div>
      <a href = "#learnmore" class = "learn-more">event</a>
    </div>          
  </div>

iPad

Desktop

3 个答案:

答案 0 :(得分:0)

如果您将始终拥有4个项目,则可以考虑max-width并使用grid而不是inline-grid,然后可以使用保证金自动居中

.inner-tile {
  display: grid;
  max-width: calc(240px * 4 + 5px * 3);
  margin: auto;
  grid-gap: 5px;
  grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
  justify-items: center;
  
  font-size: 18px;
  padding-bottom: 10px;
}

.event {
  border: 1px solid grey;
  border-radius: 4px;
  min-width: 240px; 
  min-height: 270px;
  width: 90%;
}
<div class="inner-tile">
  <div class="event">
    <div class="event-image"></div>
    <a href="#learnmore" class="learn-more">event</a>
  </div>
  <div class="event">
    <div class="event-image"></div>
    <a href="#learnmore" class="learn-more">event</a>
  </div>
  <div class="event">
    <div class="event-image"></div>
    <a href="#learnmore" class="learn-more">event</a>
  </div>
  <div class="event">
    <div class="event-image"></div>
    <a href="#learnmore" class="learn-more">event</a>
  </div>
</div>

答案 1 :(得分:0)

使用

   grid-template-columns: 1fr 1fr 1fr 1fr;
   justify-items: center;

有关更多信息,请参见https://alligator.io/css/align-justify/

答案 2 :(得分:-1)

对于外部div使用justify-content: center; css代码而不是justify-items: center;