如何在CSS网格中居中放置图像

时间:2020-07-10 23:03:10

标签: html css

我正在尝试将图像放在CSS网格中居中,并使图像覆盖整个容器。这是html和css代码,

.object-wrapper {
  display: grid;
  grid-template-columns: repeat(45, 1fr);
  grid-template-rows: repeat(60, 1fr);
  grid-gap: 0px;
  max-width: 550px;
  max-height: 720px;
  justify-content: center;
}

.object-wrapper div {
  background: transparent;
  padding: 5px;
  max-height: 5px;
  max-width: 5px;
  text-align: center;
  border: 0.001px solid whitesmoke;
  font-size: 5px;
}

img {
  max-height: 100%;
  text-align: center;
  margin-left: auto;
  margin-right: auto;
  display: block;
  object-fit: cover;
}
<div id="object">
  <div class="object-wrapper">
    <div><img src="troll.jpg"></div>
    <div><img src="troll.jpg"></div>
    <div><img src="troll.jpg"></div>
    <div><img src="troll.jpg"></div>
    <div><img src="troll.jpg"></div>
    <div><img src="troll.jpg"></div>
    <div><img src="troll.jpg"></div>
    <div><img src="troll.jpg"></div>
    <div><img src="troll.jpg"></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>
    <div></div>

显示时,图像显示在网格的相交中间。

任何帮助将不胜感激,谢谢!

1 个答案:

答案 0 :(得分:0)

取消div的最大高度/宽度,并将包装器的显示设置为display: inline-grid

链接到CSS Grid上的更多内容

下面带有注释的示例

<!DOCTYPE html>
<html>
<head>
    <title>Test</title>
    <style type="text/css">
        .object-wrapper {
            /*display inline-grid*/
            display: inline-grid;
            grid-template-columns: repeat(45, 1fr);
            grid-template-rows: repeat(60, 1fr);
            grid-gap: 0px;
            max-width: 550px;
            max-height: 720px;
        }

        .object-wrapper div {
            background: transparent;
            text-align: center;
            border: 0.001px solid whitesmoke;
            font-size: 5px;
        }

        img {
            max-height: 100%;
            text-align: center;
            display: block;
            object-fit: cover;
            height: 100px;
            width: 100px;
        }
    </style>
</head>
<body>


<div id="object">
    <div class="object-wrapper">
        <div><img src="https://jessehouwing.net/content/images/size/w2000/2018/07/stackoverflow-1.png"></div>
        <div><img src="https://jessehouwing.net/content/images/size/w2000/2018/07/stackoverflow-1.png"></div>
        <div><img src="https://jessehouwing.net/content/images/size/w2000/2018/07/stackoverflow-1.png"></div>
     <div><img src="https://jessehouwing.net/content/images/size/w2000/2018/07/stackoverflow-1.png"></div>
     <div><img src="https://jessehouwing.net/content/images/size/w2000/2018/07/stackoverflow-1.png"></div>
     <div><img src="https://jessehouwing.net/content/images/size/w2000/2018/07/stackoverflow-1.png"></div>
     <div><img src="https://jessehouwing.net/content/images/size/w2000/2018/07/stackoverflow-1.png"></div>
     <div><img src="https://jessehouwing.net/content/images/size/w2000/2018/07/stackoverflow-1.png"></div>
    </div>
</div>


</body>
</html>