如何让文本始终固定在卡片右上角?CSS布局问题求助
解决卡片右上角“Nouveau”定位问题
你的问题出在没有给position: absolute元素设置基于父容器的精准偏移规则,导致不同屏幕尺寸下位置失控。以下是修正后的方案:
修改后的SCSS代码
.home-restaurants background-color: #F6F6F6 &_card margin: 18px position: relative // 可选:防止极端小屏幕下标签溢出 overflow: hidden img display: flex background-color: white border-radius: 15px 15px 0 0 width: 100% height: 231px object-fit: cover &-content line-height: 5px padding: 5px 0 5px 15px background-color: white border-radius: 0 0 15px 15px .nouveau position: absolute // 核心:开启绝对定位 top: 15px // 固定距离父容器顶部的偏移 right: 15px // 固定距离父容器右侧的偏移 z-index: 1 // 确保标签显示在图片上方 display: flex justify-content: center align-items: center // 修正:垂直居中用align-items,原align-content无效 border-radius: 5px color: #008766 background-color: #99E2D0 padding: 7px width: 80px
关键修改说明
- 给
.nouveau添加position: absolute,并通过top和right固定相对于父容器(.home-restaurants_card已设position: relative)的偏移量,无论屏幕尺寸变化,都会稳定保持在右上角。 - 修正
align-items: center,确保文字在标签内垂直居中,原align-content仅适用于flex容器有多行元素的场景。 - 新增
z-index: 1,避免标签被下方的图片遮挡。 - 可选给
.home-restaurants_card加overflow: hidden,极端小屏幕下可强制裁剪超出卡片的部分。
HTML代码无需修改,保持原有结构即可。
内容的提问来源于stack exchange,提问作者8bitmd
相关产品推荐
相关产品推荐

