如何使用CSS网格重新创建浮动布局? [英] How to recreate float layout using css grid?

查看:127
本文介绍了如何使用CSS网格重新创建浮动布局?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个布局,左边有一个图像,右边有一些文本内容。它的布局如下所示:

I have a layout with an image on the left and some text content on the right. It is laid out something like this:

.left {
  max-width: calc(100% - 150px);
  float: left;
}

img {
  width: 300px;
  max-width: 100%;
}

<div class="wrapper">
  <div class="left"><img src="https://i.stack.imgur.com/W6Sd8.png" /></div>
  <div class="right">Hello, I am Kitteh</div>
</div>

基本思想是图像可以最大300px ,但必须始终至少保留150px,以使文本内容位于右侧。文本内容将填充尽可能多的空间-图像始终至少保留150px。

The basic idea is that the image can be up to 300px but must always leave at least 150px for the text content to the right. The text content will fill up as much space as possible - which will always be at least 150px left by the image.

我的目标是使用CSS网格重新创建此内容,但是我对如何使用 grid-template-columns 来获得相同的行为感到困惑。此刻我有这样的事情:

My goal is to recreate this using CSS grid, but I am confused by how to use grid-template-columns to get the same behaviour. At the moment I have something like this:

.wrapper {
  display: grid;
  grid-template-columns: auto minmax(150px, auto);
}

img {
  width: 300px;
  max-width: 100%;
}

<div class="wrapper">
  <div class="left"><img src="https://i.stack.imgur.com/W6Sd8.png" /></div>
  <div class="right">Hello, I am Kitteh</div>
</div>

这尊重右侧列的最小150px,但不会扩展以满足图像要求。

This respects the 150px minimum for the right hand column, but doesn't expand to meet the image. How can I get the grid layout to behave the same as the floats in my first example?

推荐答案

,而不是<$ c $,如何使网格布局的行为与第一个示例中的浮点数相同? c> minmax(150px,auto); 添加 minmax(150px,1fr)

fr 单位将占据剩余的空间。

fr unit will take the space which is left.

fr单位就像是百分比(%)。但是他们为我们做了艰苦的工作。例如,如果您希望4列大小相同,则可以执行25%25%25%25%。类似于1fr 1fr 1fr 1fr。

fr unit is like persentages (%). But they do the hard work for us. For example if you want 4 columns same size you can do 25% 25% 25% 25%. Which will be similar to 1fr 1fr 1fr 1fr.

但是如果您有 grid-gap:20px ,您会注意到如果您使用劝导,则会出现一个滚动。幸运的是,fr单位将负责此工作,并且不会出现滚动。

But if you have grid-gap: 20px you will notice a scroll will appear if you use persentages. Fortunately fr unit will take care of this and no scroll will appear.

grid-template-columns:200px 1fr ,转换为说服力将是
grid-template-columns:200px calc(100%-200px),因此fr单位再次为我们做着艰苦的工作

Also grid-template-columns: 200px 1fr, to converted to persentages will be grid-template-columns: 200px calc(100% - 200px) so again fr unit is doing the hard work for us.

您可以将fr单元视为自由空间,因为它正在获取可用空间并为我们做一些辛苦的工作。

You can think the fr unit as free space since it is getting the available free space and doing some hard work for us.

可以获得足够的能量吗? 查看超赞的CSS网格视频系列

Can get enough? Check out awesome css grid video series

希望这会对您有所帮助。

Hope this will help you.

在此处查看操作

这篇关于如何使用CSS网格重新创建浮动布局?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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