How to make images stay within the rows of a css grid container?

前端 未结 3 464
渐次进展
渐次进展 2020-11-28 14:58

The code below shows the intended behavior when I resize the window in Chrome 60, and in Firefox 55 (but not in iOS Safari 10.3; that is most likely another question why it

3条回答
  •  我在风中等你
    2020-11-28 15:08

    I don't know how snugly you want the images to fit, but you could use minmax(). minmax() lets you set a minimum and maximum value for the grid-row size. Setting auto for the min and 33% for the max will let them get as small as the content needs to get, and up to 33% of the height of the grid container, but no bigger. This will keep all your grid items together at maximum height of 99% of the 60vh that the grid container takes up.

    This is not exactly the automatic way you were hoping to get... you're still declaring a size, even if it's relative. It does avoid the clunky-looking calc((60vh - 12px) / 3), though there's nothing really wrong with using that method, unless there are other constraints in your post.

    However, kukkuz' answer and resetting the min-height is a better solution and is what I was missing.

    html, body {
      width: 100%;
      height: 100%;
      padding: 0;
      margin: 0;
      border: 0;
      background-color: lightgrey;
    }
    .container {
      box-sizing: border-box;
      width: 100%;
      display: grid;
      grid-template-columns: 1fr 1fr;
      grid-template-rows: repeat(3, minmax(auto, 33%));
      height: 60vh;
      border: 3px solid yellow;
      padding: 3px;
    }
    .tile {
        display: grid;
    }
    img {
      box-sizing: border-box;
      display: block;
      object-fit: contain;
      width: 100%;
      height: 100%;
      margin: 0;
      border: 0;
      padding: 3px;
    }
     
     
    .
    .
    .
    .
    .
    .

提交回复
热议问题