Skip to content

图片自适应不变形(至少3种)

1. 使用 object-fit 属性

css
img {
  width: 100%;
  height: 200px;
  object-fit: cover; /* 保持宽高比并覆盖容器 */
  /* 其他值:contain(保持宽高比并适应容器)、fill(拉伸填充容器) */
}

2. 使用 padding-top + background-image

css
.image-container {
  position: relative;
  width: 100%;
  padding-top: 75%; /* 4:3 宽高比 */
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
}
html
<div class="image-container" style="background-image: url('image.jpg');"></div>

3. 使用 max-width 和 max-height

css
img {
  max-width: 100%;
  max-height: 100%;
  width: auto;
  height: auto;
}

.container {
  width: 300px;
  height: 200px;
  display: flex;
  justify-content: center;
  align-items: center;
  border: 1px solid #ccc;
}

4. 使用 Flexbox 布局

css
.container {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 300px;
  height: 200px;
  border: 1px solid #ccc;
}

.container img {
  max-width: 100%;
  max-height: 100%;
  width: auto;
  height: auto;
}

基于 VitePress 的本地知识库