How to recreate float layout using css grid?

痞子三分冷 提交于 2019-12-12 06:48:32

问题


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>

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.

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>

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?


回答1:


instead of minmax(150px, auto); add minmax(150px, 1fr)

fr unit will take the space which is left.

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.

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.

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.

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

Can get enough? Check out awesome css grid video series

Hope this will help you.

See it in action here



来源:https://stackoverflow.com/questions/52300624/how-to-recreate-float-layout-using-css-grid

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