Auto-adjusting columns with CSS grid

♀尐吖头ヾ 提交于 2019-12-10 15:58:30

问题


I'm trying to work out whether CSS grid is capable of behaving like a table.

So if I have a long piece of "cell data" (col 2) and there's space available elsewhere in the table, I don't want it to wrap as it does in the image below:

What I want to achieve is something like this. Where the column with the longer piece of content grows and the other columns shrink based on the content in that column.

I've uploaded an example here on CodePen: https://codepen.io/anon/pen/WdNJdY

.wrapper {
  display: grid;
  grid-template-columns: 33.33% 33.33% 33.33%;
  background-color: #fff;
  color: #444;
  max-width: 800px;
}

.box {
  background-color: #444;
  color: #fff;
  border-radius: 5px;
  padding: 20px;
  font-size: 150%;
}
<div class="wrapper">
  <div class="box a">col 1</div>
  <div class="box b">col 2</div>
  <div class="box c">col 3</div>
  <div class="box d">short data</div>
  <div class="box e">a really long piece of data</div>
  <div class="box f">short data</div>
</div>

I'm very new to CSS grid so I'm curious if this is possible.

Any help is appreciated. Thanks in advance!


回答1:


Instead of setting your columns to 33%...

.wrapper {
  display: grid;
  grid-template-columns: 33.33% 33.33% 33.33%;
}

... which sets a fixed width, have each column use available space:

.wrapper {
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
}

Then, prevent your text from wrapping:

.box { white-space: nowrap; }

.wrapper {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  background-color: #fff;
  color: #444;
  max-width: 800px;
}

.box {
  white-space: nowrap;
  background-color: #444;
  color: #fff;
  border-radius: 5px;
  padding: 20px;
  font-size: 150%;
}
<div class="wrapper">
  <div class="box a">col 1</div>
  <div class="box b">col 2</div>
  <div class="box c">col 3</div>
  <div class="box d">short data</div>
  <div class="box e">a really long piece of data</div>
  <div class="box f">short data</div>
</div>

More details here: The difference between percentage and fr units in CSS Grid Layout




回答2:


The answer turned out to be pretty simple when I stopped thinking about it. The question answered itself, you can use auto as col width instead of percentages or fractions.

Try grid-template-columns: repeat(3, auto);

See: https://codepen.io/anon/pen/baGKYb (tested in chrome)

Oh grid, is there anything you can't do?



来源:https://stackoverflow.com/questions/47778148/auto-adjusting-columns-with-css-grid

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