Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
921 views
in Technique[技术] by (71.8m points)

responsive design - CSS Grid - Span two columns unless the row holds only one

The problem

I'm struggling to make a relatively simple CSS Grid layout truly responsive. Here's what I want to achieve:

  1. Layout an image next to some text with a 1/3 - 2/3 split, i.e. the image takes one third of the available space, the text two thirds.
  2. Limit the minimum width of the image and the text to a fixed value (like 15rem).
  3. Have the text automtically wrap to the next row if the available space goes below the threshold where it fits next to the image (based on the minimum widths and and the column gaps).

Important constraint: I want the layout to wrap based on container widths, not on viewport widths, so using media queries is not an option.

My attempts

The 1/1 - 2/3 split is simple:
grid-template-columns: 1fr 2fr

But that approach doesn't allow for a minimum column width, so this needs to be modified using the RAM approach, so we can fit as many columns as we want:
grid-template-columns: repeat(auto-fit, minmax(15rem, 1fr));

Then we can simply tell the image to span one column, the text to span two columns:

.one-column {
    grid-column: span 1;
}
.two-columns {
    grid-column: span 2;
}

Now here's the problem: span 2 will create a zero-width implicit column on small container sizes when there is only space for one column, resulting in a broken layout, the text being wider than the image by the width of the column gap. As far as I can tell, telling the text to span 2 only if two explicit columns are available is not possible.

Here's a codepen with the problem:

https://codepen.io/MoritzLost/pen/NWRZNgz

I'm surprised that there doesn't seem to be a truly responsive solution to this relatively simple layout. All the examples for responsive grids that I found online don't seem to take into account grids with uneven column-spans, or if they do they use media queries to fix the resulting problem. Is there a way the above example can be fixed? Or is there a better approach to achieve the desired layout without using media queries? Thanks!

question from:https://stackoverflow.com/questions/65874196/css-grid-span-two-columns-unless-the-row-holds-only-one

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...