簡體   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