Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

css将图片设置为正方形 #34

Open
GIScyw opened this issue May 19, 2023 · 0 comments
Open

css将图片设置为正方形 #34

GIScyw opened this issue May 19, 2023 · 0 comments

Comments

@GIScyw
Copy link
Owner

GIScyw commented May 19, 2023

需求:后端返回了一组图片,图片的宽度固定,高度不固定。前端要求图片展示为正方形,图片不能变形且自适应,如果图片高了则裁剪掉。

<div>
  <div class="img-wrap">
       <img src="">
   </div>
</div>

.img-wrap {
        position: relative;
        width: 100%;
        height: 0;
        padding-bottom: 100%;
        overflow: hidden;

}

.img-wrap img  {
        position: absolute;
        width: 100%;
        //height: 100%;
}

原理解析:img-wrap继承父元素的宽度,为了保证img-wrap容器的高度等于宽度,通过padding-bottom撑开高度,接下来图片只设置宽度让它等于父元素的宽度,图片的高度会自适应。父元素设置overflow:hidden,这样设置以后图片即使过高也能保证不变形,只是看起来像裁剪成了正方形。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant