返回博客

CSS 图片比例设置方法

本文介绍两种使用 CSS 设置图片比例的方法:第一种方法使用 `width`、`height`、`object-fit: cover` 属性;第二种方法使用 `aspect-ratio` 属性。两种方法都能有效控制图片比例,避免图片变形。

Mt.r
|

CSS 设置图片比例

<div class="container">
  <img src="https://img-blog.csdnimg.cn/2021012411095991.png" alt="" />
</div>

<style>
  .container {
    width: 100px;
    height: 100px;
    border: 1px solid;
    overflow: hidden;
  }
  img {
    width: 100%;
    height: 100%;
    object-fit: cover;
  }
</style>

另一个方法 aspect-ratio

<div class="container">
  <img src="https://img-blog.csdnimg.cn/2021012411095991.png" alt="" />
</div>

<style>
  .container {
    width: 100px;
    height: 100px;
    border: 1px solid;
    overflow: hidden;
  }
  img {
    width: 100%;
    height: 100%;
    aspect-ratio: 1;
  }
</style>