我正在尝试垂直对齐网格中的图像。我正在使用带有图像标题的
<figure>
HTML 元素。图像取代了复选框。
请看我的小提琴:https://jsfiddle.net/mauricederegt/do6ne2xh/129/
如您所见,4 个图像排成一行(这是正确的),但位于页面顶部。我希望它垂直居中(而且当添加另一行时,两行都应该在中间对齐)。我尝试过类似的事情:
display: flex;
align-items: center;
但似乎没有任何效果。我错过了什么?
问题在于
div
的高度,在此之前我们应该照顾它的父级 body
以及更高的级别,html
:
所以:
html, body {
height: 100%;
}
.grid {
height: 100%;
align-items: center;
}
这是工作示例:https://jsfiddle.net/s9pyLe07/1/
还有代码片段:
html,
body {
height: 100%;
}
/* @media (min-width: 600px) { */
.grid {
display: grid;
grid-template-columns: 1fr 1fr 1fr 1fr;
gap: 2%;
padding: 1%;
height: 100%;
align-items: center;
}
/* } */
figure.item {
border: 1px solid #000;
/* To horizontally center images and caption */
text-align: center;
margin: 0;
padding: 0;
}
/* hack to make images flexible: width: 100%;*/
img {
width: 100%;
}
.caption {
/* visibility: hidden; */
}
img,
figcaption {
transition-duration: 0.2s;
transform-origin: 50% 50%;
opacity: 0.5;
}
:checked+label img,
:checked+label figcaption {
opacity: 1;
}
input[type=checkbox] {
display: none;
}
<div class="grid">
<figure class="item">
<input type="checkbox" id="1" class="box" />
<label for="1">
<img src="https://picsum.photos/seed/100/100" />
<figcaption>Text below the image1</figcaption>
</label>
</figure>
<figure class="item">
<input type="checkbox" id="2" class="box" />
<label for="2">
<img src="https://picsum.photos/seed/100/100" />
<figcaption>Text below the image1</figcaption>
</label>
</figure>
<figure class="item">
<input type="checkbox" id="3" class="box" />
<label for="3">
<img src="https://picsum.photos/seed/100/100" />
<figcaption>Text below the image1</figcaption>
</label>
</figure>
<figure class="item">
<input type="checkbox" id="4" class="box" />
<label for="4">
<img src="https://picsum.photos/seed/100/100" />
<figcaption>Text below the image1</figcaption>
</label>
</figure>
</div>