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

前端 未结 3 446
渐次进展
渐次进展 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:21

    You can use grid-template-rows: 1fr 1fr 1fr and more importantly you have to reset the min-width and min-height values of the grid items which defaults to auto (as much as the content).

    To provide a more reasonable default minimum size for grid items, this specification defines that the auto value of min-width/min-height also applies an automatic minimum size in the specified axis to grid items whose overflow is visible and which span at least one track whose min track sizing function is auto. (The effect is analogous to the automatic minimum size imposed on flex items.)

    Source: W3C

    This is similar to the auto flex item rule with flexboxes. See demo below where I reset them to zero:

    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: 1fr 1fr 1fr;
      height: 60vh;
      border: 3px solid yellow;
      padding: 3px;
      /*grid-gap: 20px;*/ /* <-- would also mess things up */
    }
    
    .tile {
      min-width: 0;
      min-height: 0;
    }
    
    img {
      box-sizing: border-box;
      display: block;
      object-fit: contain;
      width: 100%;
      height: 100%;
      margin: 0;
      border: 0;
      padding: 3px;
    }
    
     
    .
    .
    .
    .
    .
    .

提交回复
热议问题