繁体   English   中英

Div中图片的垂直对齐

[英]Vertical alignment of Pictures in Div

在此处输入图片说明

从上图可以看到,如何将它们垂直对齐到灰色框的中间,在那里它们的顶部和底部的高度相等。

码:

<div style="height: 290px; width: 210px; background-color: grey;">
    <img src="${ImagePopulator}${MainProductImage}"style="padding: 20px 0;"/>
    <img src="${ImagePopulator}${MainProductImage}"style="padding: 20px 0;"/>
</div>

我尝试了上述样式,但似乎只能调整图片的顶部。 我无法使它与中间对齐。 任何帮助将非常感激。 谢谢

由于默认情况下图像是嵌入式元素,因此在这种情况下,可以使用适用于CSS垂直居中文本的方法。

例如,使用line-height可以像这样工作:

<div style="height: 290px; width: 210px; background-color: grey; line-height:250px;">
    <img src="${ImagePopulator}${MainProductImage}"style="padding: 20px 0;"/>
    <img src="${ImagePopulator}${MainProductImage}"style="padding: 20px 0;"/>
</div>

使用弹性盒也可以正常工作。 如果您愿意将img设置为block元素,则可以使用其他技巧,例如transform或negative margin

例如:

<div style="height: 290px; width: 210px; background-color: grey; position: relative;">
    <img src="${ImagePopulator}${MainProductImage}"style="display: block; margin-top:-145px;top 50%; position:relative; height: 100%; padding: 20px 0;"/>
    <img src="${ImagePopulator}${MainProductImage}"style="display: block; margin-top:-145px;top 50%; position:relative; height:100%; padding: 20px 0;"/>
</div>

将这些CSS添加到要在中心对齐的元素。

position: relative;
top: 50%;
transform: translateY(-50%);

看这个小提琴

您可以尝试此CSS-

display: flex; or, -webkit-flex
justify-content: center;
align-items: center;
flex-direction: column; or, row

使用以下样式,添加到您的代码中:

<div style="height: 290px; width: 210px; background-color: grey; display:table-cell; vertical-align:middle; text-align:center">
    <img src="https://encrypted-tbn1.gstatic.com/images?q=tbn:ANd9GcTKfww8iUXidrKRO9vnHq3rWTJdcXK8YCIhSPTMxrQ9yD1EdlnX" style="padding: 20px 0;"/>
</div>

这是上面的代码的工作示例

产生以下内容:

在此处输入图片说明

你可以这样尝试

 .block{ display: table-cell; vertical-align: middle; height: 120px; background: rgba(0,0,0,.3); } img{ height: 30px; } 
  <div class="block"> <img src="https://raw.githubusercontent.com/ModernPGP/icons/master/keys/icon-fingerprint.png"> </div> 

使用display: table-cell您可以使用vertical-align CSS属性

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM