如何垂直对齐各种高度的网格元素?

时间:2019-11-15 00:18:56

标签: html css flexbox

我的问题是我的网格元素都具有不同的高度长度,这在下面的行下方留有多余的空间。它看起来确实像我希望在移动设备上显示的样子,但是在台式机上,我似乎无法将图像向上推到有多余空间的地方。

我尝试使用display: flex; align-items: flex-start;,但仍然留有多余的空格。

请访问我的网站以查看:https://eylenkim.github.io/ArtByEylen/Portfolio/portfolio.html

这是我的代码:

示例HTML

<div class="grid">
    <div class="item">
        <div class="item-content">
            <img src="myimage1.JPG" style="height:auto; width: 100%">
        </div>
        <div class="item-content">
            <img src="myimage2.JPG" style="height:auto; width: 100%">
        </div>
    </div>
</div>

CSS

.grid {
  position: relative;
  display:flex;
  justify-content:center;
  flex-wrap:wrap;
  align-items: flex-start;
  margin: 0 5% 0 5%;
}

.item {
  /*position: absolute; */
  max-width: 400px;
  width:400%;
  height: auto;
  z-index: 1;
  transition: transform 0.6s ease;
  cursor: pointer;
  margin: 5px;
  overflow: hidden;
}

img {
  max-width:400px !important;
       -o-object-fit: cover;
  object-fit: cover;
  -webkit-transform: scale(1);
  -ms-transform: scale(1);
  transform: scale(1);
  -webkit-transition: all 0.3s ease-in-out;
  -o-transition: all 0.3s ease-in-out;
  transition: all 0.3s ease-in-out;
}

.item img:hover {
  -webkit-transform: scale(1.03);
    -ms-transform: scale(1.03);
    transform: scale(1.03);
}

.item-content {
  cursor: pointer;
  position: relative;
  width: 100%;
  height: 100%;
}

2 个答案:

答案 0 :(得分:1)

我最近使用了非常依赖flex box的前端接口。但是,我需要各种控件具有完全相同的高度的内容。因此,我选择使用一个网格,该网格也具有响应能力,并且还具有网格间隙(因此您不必在图像中添加填充)

当细胞被压下时,flex Box不能提供与其他细胞相同的尺寸。对于Grid,它们保留与网格中所有其他单元相同的大小。因此,它应该可以解决您在底部留有空白的问题

Flex Box and Grid

这是使网格正常工作的CSS和代码

Grid Vs FlexbBox

答案 1 :(得分:0)

我建议您必须在此使用flexbox。也许尝试在您的.grid类上使用以下代码行:

.grid {
    width: 100%;
    display: -ms-flexbox;
    -ms-flex-direction: column;
    -ms-flex-wrap: wrap;
    flex-direction: column;
    flex-wrap: wrap;
    column-count: 5;
    height: auto !important;
}

然后,.item类上的这一行代码:

.item {
    height: auto;
    z-index: 1;
    cursor: pointer;
    margin: 5px;
    overflow: hidden;
}

您在.item上的宽度太大,不要忘记拥有column-count