Set minimum and maximum widths to grid column using percentages

巧了我就是萌 提交于 2021-01-05 06:44:46

问题


When I set the first column in a CSS grid column to a minimum percentage, the column width does not observe the minimum. Example:

grid-template-columns: minmax(50%, 75%)  1fr;

With these values, as the viewport narrows the first column keeps shrinking horizontally until it finally collapses and disappears. Likewise, stretching the screen makes the first column wider as you go, so that eventually its wider than 3/4 of the total grid width.

(Even so, at most grid widths the proportions of the two columns do correspond, roughly, to what I'm trying to achieve.)

So is there a way to make a first column whose width is always, say, at least half of the grid width, and never more than 2/3?

Notes:

  • Grid-gap is 0 for now so as avoid complicating the percentage computations.
  • I know that I can set the minimum width to a fixed number of pixels and thereby enforce a minimum width -- the column won't disappear. But then as the grid narrows the maximum % constraint is violated. Besides, I'm trying not to use fixed pixel widths.

My code (grid-gap added to show column boundaries):

.wrapper {
  display: grid;
  grid-template-columns: minmax(50%, 75%) 1fr;
  grid-gap: 1px;
  padding: 10px;
  background-color: #219643;
}

.item {
background-color: rgba(255, 255, 255, 0.8);
  text-align: center;
  padding: 20px 0;
  font-size: 30px;
}
<div class="wrapper">
  <div class="item">Column 1</div>
  <div class="item">Column 2</div>
</div>

回答1:


Your original code looks fine. I believe it should work. Why it doesn't isn't entirely clear to me.

I'll say this: We're just at Grid Level 1. It's brand new tech, so you should expect some glitches and limitations.

For example, in your minmax(50%, 75%), the track will always default to the max value.

  • minmax() defaulting to max

This removes minmax() as a useful option in many layouts, as many people want a min default.

Why doesn't the minimum percentage work? I think it has something to do with the width of the parent container (no settings I tried worked), or something with the grid track sizing algorithm. Again, it's unclear.

So I just skipped over all that, giving the browser the same commands in a different way. This seems to work:

.wrapper {
  display: grid;
  grid-template-columns: minmax(50%, 1fr) 25%;
  grid-gap: 1px;
  padding: 10px;
  background-color: #219643;
}

.item {
  background-color: rgba(255, 255, 255, 0.8);
  text-align: center;
  padding: 20px 0;
  font-size: 30px;
}
<div class="wrapper">
  <div class="item">Column 1</div>
  <div class="item">Column 2</div>
</div>


来源:https://stackoverflow.com/questions/65399446/set-minimum-and-maximum-widths-to-grid-column-using-percentages

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