CSS Grid auto-fill columns of different widths

不羁的心 提交于 2021-02-07 12:55:33

问题


Rather than rely on media queries, I've been trying to create a responsive component using css grid so that it'll make use of available space in different layouts. If the space is large enough there should be two columns, the first is fixed width (containing an image) and the second takes the remainder (with text), a 2x1 grid. If it's not then there should be a single column taking all available space and the grid changes to 1x2, e.g.

Wide 2x1 grid

+---+---------+
| o | text    |
+---+---------+

Narrow 1x2 grid

+---------+
|    o    |
+---------+
| text    |
+---------+

I looked at using repeat(auto-fill, ...) with multiple column dimensions but then it repeats that 2 column pattern, which makes sense but doesn't solve my problem. I'm hoping there's a way to define different widths for different auto-fill columns. Otherwise, I suspect there might be a solution involving *-content? Is what I'm trying to do possible?


回答1:


Paulie_D, you're correct that this is better handled with flexbox, but it turns out it doesn't need media queries. Basically needs a combination of flex-wrap: wrap and different flex-grow values so the text takes the remaining space when it doesn't wrap but the image can still grow when stacked.

Example

.Profile {
  display: flex;
  flex-wrap: wrap;
  padding: .5rem;
}
.Profile-img {
  flex: 1 0 0;
  background: blue;
  margin: .5rem;
}
.Profile-text {
  flex: 10 0 10em;
  background: red;
  margin: .5rem;
}
img {
  width: 100px;
  height: 100px;
  background: black;
  display: table;
  margin: 0 auto;
}
<div style="width: 600px">
  <div class="Profile">
    <div class="Profile-img">
      <img/>
    </div>
    <div class="Profile-text">
      Text
    </div>
  </div>
</div>
<div style="width: 300px">
  <div class="Profile">
    <div class="Profile-img">
      <img/>
    </div>
    <div class="Profile-text">
      Text
    </div>
  </div>
</div>


来源:https://stackoverflow.com/questions/49402930/css-grid-auto-fill-columns-of-different-widths

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