Boxes with fixed span to fill entire column

。_饼干妹妹 提交于 2019-12-13 03:45:17

问题


I am a first time CSS-Grid user:

What I try to achieve is to have a flexible box system using a 3-column grid to which I can simply add boxes of the size of 1, 2 or 3 columns; just using one class.

I tried to achieve this by doing this https://codepen.io/mathil/pen/WXarXB :

.container {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  grid-gap: 12px;
  width: 50%;
  margin-right: auto;
  margin-left: auto;
  background: grey;
}

.card-fullspan {
  grid-column: span 3;
}

.card-twothirdspan {
  grid-column: span 2;
}

.card-thirdspan {
  grid-column: span 1;
}
<div class="container">
  <div class="card-fullspan" style="background: red">Fullspan</div>
  <div class="card-twothirdspan" style="background:green">
    twothirdspan
  </div>
  <div class="card-thirdspan" style="background:green">
    thirdspan
  </div>
</div>

I know that I have to span it for 4, which would be this for the fullspan:

.card-fullspan {
  grid-column: span 4;
}

But of course this does not work with the other two, since I wont be able to come to arrive at the sum of for with a combination of the other boxes. There will always be the 12px Gutter on the right side.

I know that it's possible to just add a different class or id to each of the items, but that wouldn't be the ideal solution.


回答1:


The span keyword counts subsequent grid lines.

So in a three column grid, when you want an item to span the full row, you specify span: 3, not span: 4, which creates an additional (implicit) column.

Your code:

.card-fullspan {
   grid-column: span 4;  /* spans across 4 columns */
}

Try this instead:

.card-fullspan {
   grid-column: span 3; /* spans across 3 columns */
}

or this:

.card-fullspan {
   grid-column: 1 / 4; /* spans from grid-column-line 1 to 4 (3 columns) */
}

or this:

.card-fullspan {
   grid-column: 1 / -1; /* spans from grid-column-line 1 from the start side
                           to grid-column-line: 1 starting from the end side
                           (note: negative integers work only with explicit grids  */
}

All the details are in the spec in this section:

  • https://www.w3.org/TR/css3-grid-layout/#line-placement

revised codepen



来源:https://stackoverflow.com/questions/47536879/boxes-with-fixed-span-to-fill-entire-column

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!