CSS水平與垂直居中

分享交流编程相关的话题?
回复
头像
ejsoon
圈圈精英
圈圈精英
帖子: 3392
注册时间: 2022年 11月 18日 17:36
为圈友点赞: 141 次
被圈友点赞: 161 次
联系:

CSS水平與垂直居中

帖子 ejsoon »

代码: 全选

要將子元素(例如 `<img>`)在父元素中水平和垂直居中,同時保持其寬高比並確保其寬高不超過父元素,可以使用 `object-fit` 和一些定位技巧來實現。以下是具體的 HTML 和 CSS 代碼:

### HTML:
```html
<div class="container">
  <img src="your-image.jpg" alt="Centered Image" />
</div>
```

### CSS:
```css
.container {
  position: fixed; /* 父元素固定 */
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  justify-content: center; /* 水平居中 */
  align-items: center;     /* 垂直居中 */
}

.container img {
  max-width: 100%;
  max-height: 100%;
  object-fit: contain; /* 保持寬高比並且不會超過父元素 */
}
```

### 說明:
1. `position: fixed;` 將父元素固定在視窗中,並且寬高設為 100% 以填滿整個視窗。
2. 使用 `display: flex` 和 `justify-content: center` / `align-items: center` 使子元素 `<img>` 在父容器中居中。
3. `max-width: 100%` 和 `max-height: 100%` 確保圖片的寬度和高度最大不超過父元素的範圍。
4. `object-fit: contain;` 保持圖片的原始寬高比並將其縮放,避免超出父元素的範圍。

這樣圖片會被保持寬高比地顯示,並且始終保持居中,無論其大小如何變化。
https://ejsoon.win/
弈趣極光:享受思維樂趣
回复

在线用户

正浏览此版面之用户: 没有注册用户 和 2 访客