Search code examples
csscss-grid

CSS Grid - Rules for a column that must be as narrow as possible but with a max width of 50%


I have a very simple grid, with two columns. The left column is a picture and the right column is some text.

I want the left column to adjust to the picture width (so the column must be as narrow as possible, as long as the picture fits). But I also want this column to take maximum 50% of the grid width.

I tried a couple of things like:

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

But that doesn't work: the left column always takes 50%, even with a small picture!

So how can I tell it to take less width if the picture is smaller?

(Please note that the width of the picture is max-width: 100%)


Solution

  • You were on the right track, you can use a combination of minmax() and max-content.

    Set the image column to a minimum of auto and a maximum of max-content while setting the text column to a minimum of 50% and a maximum of auto.

    grid-template-columns: minmax(auto, max-content) minmax(50%, auto);
    

    The minimum of 50% on the text column will ensure that the picture is never wider than 50%, while the maximum of auto ensures that the text will grow larger when the image is less than 50% wide.

    On the other hand, the minimum of auto on the image will ensure that it adjusts to fit to the image's size when less than 50%... while the maximum of max-content allows the text column to extend all the way passed 50% to meet the image's intrinsic width.

    You could also use fit-content() for the image column instead of minmax(auto, max-content), but that amounts to the same thing (see https://developer.mozilla.org/en-US/docs/Web/CSS/fit-content).

    Here a snippet:

    #grid {
      display: grid;
      grid-template-columns: minmax(auto, max-content) minmax(50%, auto);
    
    }
    img {
      max-width: 100%;
    }
    .grid-item {
      border: 1px solid red;
    }
    <div id="grid">
      <img class="grid-item"src="https://via.placeholder.com/150" alt="">
      <p class="grid-item">Some Text</p>
    </div>

    To test you can adjust the number at the end of the placeholder image URL to make it bigger or smaller. Here in fiddle form: https://jsfiddle.net/98gme470/

    Note the lacking support for max-content and fit-content() in IE: https://caniuse.com/#search=max-content