首頁  >  文章  >  web前端  >  如何在保持高度和縱橫比的同時使圖像在父 Div 中居中?

如何在保持高度和縱橫比的同時使圖像在父 Div 中居中?

Barbara Streisand
Barbara Streisand原創
2024-10-24 02:30:29858瀏覽

How to Center an Image within a Parent Div While Preserving Height and Aspect Ratio?

在父 div 中居中圖片元素

在其父 div 中居中圖片需要特定的 CSS 技術。以下是實現此目的的方法:

問題:

如何在其父div 中間對齊圖像,同時保留其高度(100%),而不拉伸其寬度?

範例:

考慮問題中提供的HTML 和CSS:

<code class="html"><div class="box">
  <img src='featured.jpg' />
</div></code>
<code class="css">.box {
  height: 100%;
  width: 450px;
  border: 2px solid red;
  background: green;
  overflow: hidden;
}
.box img {
  height: 100%;
  width: auto;
  text-align: center;
}</code>

解決方案

要使圖像居中,請添加text-align: center;對父div 而不是子圖像元素的CSS 聲明:

<code class="css">.box {
  /* ... */
  text-align: center;  /* Align center all inline elements */
}</code>

這會將div 內的所有內聯元素(包括圖像)居中。

其他增強功能:

由於行內元素預留的行高,影像下方可能會有間隙。若要消除此間隙,請新增vertical-align:bottom;到圖像CSS:

<code class="css">.box img {
  /* ... */
  vertical-align: bottom;  /* Fix the vertical gap */
}</code>

以上是如何在保持高度和縱橫比的同時使圖像在父 Div 中居中?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn