Могу ли я центрировать сетку автозаполнения чистой CSS? - PullRequest
0 голосов
/ 31 марта 2020

Я пытаюсь заполнить свою страницу горизонтально как можно большим количеством блоков и центрировать результат.

Я хочу, чтобы сетка могла изменять размеры, когда окно становится меньше:

wide window
xxx

small window
xx
x

Этого можно достичь без javascript?

.box {
  box-sizing: border-box;
  
  width: 200px;
  height: 150px;
  
  background-color: white;
  border: solid 6px red;
}

.box:nth-child(2) {
  background-color: blue
}

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, 200px);
}
<div class="center">
  <div class="grid">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
  </div>
</div>

Объяснение желаемого центрирования визуально:

Может ли выделенная желтым цветом область равномерно распределяться с обеих сторон? enter image description here


Требуемое выравнивание ящика: enter image description here

Ответы [ 3 ]

2 голосов
/ 31 марта 2020

По какой-то причине это работает только в chrome.


Для автоматической подгонки и автозаполнения требуется известная ширина для вычисления, мы можем сделать это с помощью max-width:100% вместо использования width, которая будет растягивать его и мешать центрированию, а также избегать фиксированной ширины.

.box {
  box-sizing: border-box;
  width: 200px;
  height: 150px;
  background-color: white;
  border: solid 6px red;
}

.box:nth-child(2) {
  background-color: blue
}

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, 200px);
  max-width: 100%;
}

.center {
  display: flex;
  flex-direction: column;
  align-items: center;
}
<div class="center">
  <div class="grid">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
  </div>
</div>

Существует странность с этим, если вы начнете с широкого viewport, а затем измените его размер на меньший, сетка не будет быть в центре из-за auto-fill

Скажем, у вас есть 3 элемента, но контейнер может уместиться в 4 с auto-fill, это создаст четвертый столбец, но у нас нет четвертого элемента, поэтому он будет выглядеть неравномерно.

Я предлагаю использовать auto-fit, который вместо создания четвертого столбца будет равномерно разделять пространство с каждой стороны.

.box {
  box-sizing: border-box;
  width: 200px;
  height: 150px;
  background-color: white;
  border: solid 6px red;
}

.box:nth-child(2) {
  background-color: blue
}

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, 200px);
  max-width: 100%;
}

.center {
  display: flex;
  flex-direction: column;
  align-items: center;
}
<div class="center">
  <div class="grid">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
  </div>
</div>

Теперь, если вы достаточно измените размер окна, вы увидите, что иногда оно распределяется неравномерно из-за относительной единицы на максимальной ширине. необходимо пересчитать ширину, потому что она основана на ширине родителя и родителя, которая основана на содержимом.

мы можем запустить этот пересчет, используя анимацию.

chrome конкретный c решение

.center {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.box {
  box-sizing: border-box;
  width: 200px;
  height: 150px;
  background-color: white;
  border: solid 6px red;
}

.box:nth-child(2) {
  background-color: blue
}

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, 200px);
  max-width: 100%;
  animation: recalc 5s linear infinite;
}

@keyframes recalc {
  to {
    max-width: 99.9%;
  }
}
<div class="center">
  <div class="grid">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
  </div>
</div>

Чтобы поддерживать как минимум FF и, возможно, некоторые другие браузеры, используйте единицы просмотра.

.box {
  box-sizing: border-box;
  width: 200px;
  height: 150px;
  background-color: white;
  border: solid 6px red;
}

.box:nth-child(2) {
  background-color: blue
}

.grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, 200px);
  max-width: 100vw;
  margin:0 auto;
}

.center {
  display: flex;
}
<div class="center">
  <div class="grid">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
  </div>
</div>
2 голосов
/ 31 марта 2020

Попробуйте это с flexbox.

.box {
  box-sizing: border-box;
  
  width: 200px;
  height: 150px;
  
  background-color: white;
  border: solid 6px red;
}

.box:nth-child(2) {
  background-color: blue
}

.grid {
  display: flex;
  justify-content: center;
  align-items: center;
}

@media screen and (max-width: 767px) {
 .grid {
   flex-wrap: wrap;
   justify-content: center;
 }
 .box {
  width: 50%
 }
}
<div class="center">
  <div class="grid">
    <div class="box"></div>
    <div class="box"></div>
    <div class="box"></div>
  </div>
</div>
0 голосов
/ 31 марта 2020

Я бы не использовал grid для этого. Используйте flex:

*{
  box-sizing:border-box; padding:0; margin:0; font-size:0;
}
html,body{
  width:100%; height:100%; background:#ccc;
}
.box{  
  width:200px; height:150px; background-color:white; border:6px solid red;
}
.box:nth-child(2n+2) {
  background-color:blue;
}
.center,.grid{
  display:flex; align-items:center; justify-content:center; height:100%;
}
.grid{
  min-width:600px; flex-wrap:wrap; align-items:center;
}
<div class='center'>
  <div class='grid'>
    <div class='box'></div>
    <div class='box'></div>
    <div class='box'></div>
    <div class='box'></div>
    <div class='box'></div>
  </div>
</div>
...