CSS Grid自动填充不同宽度的列 [英] CSS Grid auto-fill columns of different widths

查看:156
本文介绍了CSS Grid自动填充不同宽度的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试不使用媒体查询,而是尝试使用css网格创建一个响应式组件,以便它可以利用不同布局中的可用空间.如果空间足够大,则应该有两列,第一列是固定宽度(包含图像),第二列是其余(带有文本),即2x1网格.如果不是,那么应该只有一列占用所有可用空间,并且网格将变为1x2,例如

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.

宽2x1网格

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

狭窄的1x2网格

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

我看过使用具有多个列尺寸的 repeat(auto-fill,...),但是随后重复了2列模式,这很有意义,但不能解决我的问题.我希望有一种方法可以为不同的 auto-fill 列定义不同的宽度.否则,我怀疑可能存在涉及 *-content 的解决方案吗?我想做的事有可能吗?

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?

推荐答案

Paulie_D,您正确地认为使用flexbox可以更好地解决此问题,但事实证明,它不需要媒体查询.基本上需要结合使用 flex-wrap:wrap 和不同的 flex-grow 值,以便文本在不换行时会占用剩余的空间,但是当图像不换行时仍然可以增长堆积.

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.

示例

.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>

这篇关于CSS Grid自动填充不同宽度的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆