垂直对齐网格容器

时间:2018-04-23 21:58:30

标签: html css css3 flexbox css-grid

我设法为我的简单布局获取网格。现在我想垂直居中。我怎么能完成它?重要提示:我的意思是整个包装器(包装容器/整个网格),而不是容器中的项目......

关于这个问题的第二个问题:这是影响"网格自动流:行密集;"?



html {box-sizing: border-box;}


body {}



.wrapper {
  display: grid;
  width: 100%;
  grid-column-gap: 5px;
  grid-row-gap: 5px;
  grid-template-columns: 20% 20% 20%;
  grid-template-rows: 25% 25% 25%;
  justify-content: center;
  align-content: center;
  grid-auto-flow: row dense;
  }


.box
   {padding: 15px;
    border: 1px solid red;
    background: grey;}



.a {grid-column: 1 / span 2;
    grid-row: 1 / span 2;}

.b {grid-column: 3; grid-row: 1}

.c {grid-column: 3; grid-row: 2;}

.d {grid-column: 1; grid-row: 3}

.e {grid-column: 2; grid-row: 3}

.f {grid-column: 3; grid-row: 3}

<div class="wrapper">

<div class="box a">
<img src="" style="">
</div>

<div class="box b">
<img src="" style="">
</div>

<div class="box c">
<img src="" style="">
</div>

<div class="box d">
<img src="" style="">
</div>

<div class="box e">
<img src="" style="">
</div>

<div class="box f">
<img src="" style="">
</div>
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分:0)

我假设您已经知道如何在css网格中垂直居中项目。

你现在可以做的是创建另一个包装器包装器div,其布局是flexbox(垂直)或grid(只有1行和1列),然后将你的包装器放在其中。

&#13;
&#13;
html {box-sizing: border-box;}

.wrapper-of-wrapper {
    position: fixed;
    width: 100%;
    height: 100%;
    
    display: flex;
    flex-flow: column nowrap;
    justify-content: center;
}

.wrapper {
   
    height: 80%;

    display: grid;
    grid-column-gap: 5px;
    grid-row-gap: 5px;
    grid-template-columns: 20% 20% 20%;
    grid-template-rows: 25% 25% 25%;
    justify-content: center;
    align-content: center;
    grid-auto-flow: row dense;
}

.box {
    padding: 15px;
    border: 1px solid red;
    background: grey;
}

.a {grid-column: 1 / span 2;
    grid-row: 1 / span 2;}

.b {grid-column: 3; grid-row: 1}

.c {grid-column: 3; grid-row: 2;}

.d {grid-column: 1; grid-row: 3}

.e {grid-column: 2; grid-row: 3}

.f {grid-column: 3; grid-row: 3}
&#13;
<div class="wrapper-of-wrapper">
    <div class="wrapper">

        <div class="box a">
            <img src="" style="">
        </div>

        <div class="box b">
            <img src="" style="">
        </div>

        <div class="box c">
            <img src="" style="">
        </div>

        <div class="box d">
            <img src="" style="">
        </div>

        <div class="box e">
            <img src="" style="">
        </div>

        <div class="box f">
            <img src="" style="">
        </div>
    </div>
</div>
&#13;
&#13;
&#13;

如果你只是希望包装器在flexbox中居中而不是用它来调整大小,请将其高度设置为auto并将flex设置为0 0 auto,以便它将按内容大小调整,并且不会缩小或增大。