uni-app项目实战笔记13--全屏页面的absolute定位布局和fit-content自适应内容宽度

发布于:2025-06-15 ⋅ 阅读:(22) ⋅ 点赞:(0)

本篇主要实现全屏页面的布局,其中还涉及内容自适应宽度。

创建一个preview.vue页面用于图片预览,写入以下代码:

<template>
	<view class="preview">
		<swiper circular>
			<swiper-item  v-for="item in 5">
				<image src="/common/images/preview1.jpg" mode="aspectFill"></image>
			</swiper-item>
		</swiper>
		<view class="mask">
			<view class="goBack"></view>
			<view class="count">3 / 9</view>
			<view class="time">
				10:10
			</view>
			<view class="date">
				10月10日
			</view>
			<view class="footer">
				<view class="box">
					<uni-icons type="info" size="28"></uni-icons>
					<view class="text">信息</view>
				</view>
				<view class="box">
					<uni-icons type="star" size="28"></uni-icons>
					<view class="text">5分</view>
				</view>
				<view class="box">
					<uni-icons type="download" size="28"></uni-icons>
					<view class="text">下载</view>
				</view>
			</view>
		</view>
	</view>
</template>

CSS部分:

<style lang="scss" scoped>
.preview {
  width: 100%;
  height: 100vh; // 全屏高度
  position: relative; // 为遮罩层定位提供参照

  swiper, image {
    width: 100%;
    height: 100%; // 轮播图撑满全屏
  }

  .mask {
    .count {
      position: absolute;
      top: 10vh; // 距顶部10%视口高度
      left: 0;
      right: 0;
      margin: auto; // 水平居中
      width: fit-content; // 宽度适应内容
      background: rgba(0,0,0,0.3); // 半透明背景
      backdrop-filter: blur(10rpx); // 磨砂效果
      
    }
   
  }
}
</style>

CSS代码说明:

height:10vh; 实现全屏高度;

top:10vh; 距顶部10vh高度;

width:fit-content让宽度自适应内容,随内容实现宽度自增减;

 position: relative; // 为遮罩层定位提供参照,提供参照方为相对定位,自身则为绝对定位。

最终效果: