在实际的项目中,很多时候图片需要以正方形(1:1)显示,但往往不是所有的图片来源都是1:1的比例,这时候需要将图片按比例裁剪缩放将居中显示。
大概的思路是:
1. 先创建一个正方形的容器,由于要实现自适应,不能直接给固定长宽,需要将宽度设置100%,padding-bottom: 100% ,这样就可以实现一个自适应的正方形的容器。
2. 通过CSS 样式将图片按比例裁剪缩放并居中显示在刚刚创建的正方形容器中。
以下是详情例子代码:
<!DOCTYPE html lang="en">
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title></title>
<link href="https://cdn.bootcdn.net/ajax/libs/twitter-bootstrap/5.2.3/css/bootstrap.min.css" rel="stylesheet">
<style>
.square-item {
position: relative;
overflow: hidden;
width: 100%;
padding-bottom: 100%;/* 设置容器的上内边距为100%,使其高度与宽度相等 */
background-color: #fff;
}
.square-item img {
position: absolute;
width: 100%;
height: 100%;
object-fit: cover; /*根据父容器的尺寸裁剪和缩放图片,以填充整个容器,并保持长宽比例不变。*/
object-position: center; /*指定对象的位置,如果不设置,则默认是center*/
background-size: cover; /*背景图片的大小,如果不设置,则默认是auto*/
background-position: center;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);/*将元素移动到中心*/
}
</style>
</head>
<body>
<div class="container">
<div class="row row-cols-1 row-cols-sm-2 row-cols-md-2 row-cols-lg-2 row-cols-xl-4 mt-5">
<div class="col mb-3">
<div class="square-item">
<img src="https://tpc.googlesyndication.com/simgad/12626027716020991208" />
</div>
</div>
<div class="col mb-3">
<div class="square-item">
<img src="https://tpc.googlesyndication.com/simgad/12626027716020991208" />
</div>
</div>
<div class="col mb-3">
<div class="square-item">
<img src="https://tpc.googlesyndication.com/simgad/12626027716020991208" />
</div>
</div>
<div class="col mb-3">
<div class="square-item">
<img src="https://tpc.googlesyndication.com/simgad/12626027716020991208" />
</div>
</div>
</div>
</div>
</body>
</html>
电脑端效果:
手机端效果:

1456

被折叠的 条评论
为什么被折叠?



