← 输入框|github.com|刷新
Skip to content

第 35 期(W3C 标准-CSS-布局排版):图片等比缩放匹配父容器尺寸 #38

Open

Description

@wingmeng

题目:

请使用纯 CSS 实现图片等比缩放最大化匹配父容器尺寸的效果:使下面的图片自适应填充父容器尺寸,同时保持宽高比。

要求:

  • 图片不能变形
  • 图片不能被剪裁
  • 图片不能溢出父容器

效果图:
image

.box {
  width: 300px;
  height: 200px;
  padding: 10px;
  border: 1px solid #ccc;
}
<div class="box">
  <img src="https://fezaoduke.github.io/fe-practice-hard/assets/pics/cartoon.png">
</div>

参考答案:

.box > img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}

拓展阅读:object-fit

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions