Почему дети в сетке CSS берут 100% по горизонтали, но только 90% по вертикали от своего контейнера? - PullRequest
2 голосов
/ 25 октября 2019

Я не понимаю, почему по горизонтали все кажется идеальным, но по вертикали, как вы можете видеть на изображении, поля нет. Если это работало для сетки, чтобы взять всю ширину:

 grid-template-columns: repeat(3, 30%);

Почему это не сработало для взятия всей высоты?:

grid-template-rows: repeat(3, 30%);

enter image description here

Это код: .box - это контейнер, а .card - это дочерние элементы:

.box{
  /*
    margin: 20vh auto;
    text-align: center;
    width: 75%;
    max-width: 650px;
    height: 60vh;
*/
    display: grid;
    grid-template-columns: repeat(3, 30%);
    grid-template-rows: repeat(3, 30%);
    grid-gap: 12px;
    justify-content: center;
}

.card{
    border: 2px solid gray;
    height: 100%;
    border-radius: 6px;
}
<div className="box">
            <Card />
            <Card />
            <Card />

            <Card />
            <Card />
            <Card />

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

Ответы [ 2 ]

2 голосов
/ 27 октября 2019

Вам необходимо установить высоту контейнера с классом box и использовать fr как единицу вместо процентов. Вам нужна высота контейнера, чтобы из нее ячейки сетки могли рассчитать свою высоту. Если вы используете fr вместо процентов, пропуски сетки сначала вычитаются из ширины / высоты контейнера до того, как оставшееся пространство будет разделено в соответствии с настройками grid-template-columns и grid-template-row. Вот рабочий пример:

<div class="box">
  <div class="card"></div>
  <div class="card"></div>
  <div class="card"></div>

  <div class="card"></div>
  <div class="card"></div>
  <div class="card"></div>

  <div class="card"></div>
  <div class="card"></div>
  <div class="card"></div>
</div>
body {
  margin: 0;
}

.box {
    background-color: hotpink;
    height: 100vh;
    width: 100vw;
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    grid-template-rows: repeat(3, 1fr);
    grid-gap: 12px;
}

.card{
    border: 10px solid gray; // even with 10px or more nothing exceeds the container boundaries any more
    //height: 100%; // you do not need this, since the height is being calculated as a fr of the container height
    //box-sizing: border-box; // if you decide to set a height nonetheless you have to change box-sizing so the borders are not taking up extra space
    background-color: skyblue;
    border-radius: 6px;
}
0 голосов
/ 25 октября 2019

Попробуйте заменить 30% на 1fr

grid-template-columns: repeat(3, 1fr);
grid-template-rows: repeat(3, 1fr);
...