// 商品container
.item-container {
width: 694.44rpx;
top: 557.64rpx;
position: absolute;
display: flex;
justify-content: flex-start;
flex-direction: column;
align-items: center;
z-index: 1;
.item-box {
width: 694.44rpx;
height: 324.33rpx;
margin-bottom: 27.78rpx;
background-color: #fff;
border-radius: 34.72rpx;
position: relative;
.badge {
position: absolute;
top: 13.89rpx;
left: -8.34rpx;
width: 104.51rpx;
height: 58.4rpx;
background-image: url("/static/remote/kanyidao/item-badge.webp");
background-size: cover;
background-repeat: no-repeat;
}
}
}
这是CSS定位的经典组合用法,主要是为了实现元素的精确定位和布局控制:
1. .item-box 使用 position: relative 的原因
- 作为定位容器:当一个元素设置为
relative时,它会成为其子元素absolute定位的参考坐标系 - 不脱离文档流:
relative定位的元素仍然占据原有空间,不会影响其他元素的布局 - 保留正常布局流:多个
.item-box可以正常垂直排列,保持布局结构完整
2. .badge 使用 position: absolute 的原因
- 精确定位:可以使用
top,left,right,bottom属性相对于.item-box进行精确位置调整 - 脱离文档流:
badge不会占据正常布局空间,不会影响.item-box内部其他元素的布局 - 实现层叠效果:可以通过
z-index控制显示层级,确保badge显示在正确位置
3. 具体到当前场景
- 你希望
.badge显示在.item-box的左上角,并向左超出-8.34rpx - 如果
.item-box不设置position: relative,那么.badge的absolute定位会相对于最近的其他已定位祖先元素(比如.item-container) - 这样就无法精确控制
.badge相对于每个.item-box的位置,导致所有.badge都显示在同一位置
简单来说,这种组合实现了:让徽章相对于每个商品卡片独立定位,同时不影响商品卡片的正常布局和排列。
这种定位方式在实际开发中非常常见,比如商品标签、通知徽章、图标提示等场景都会用到。