逻辑层与生命周期

微信小程序教程 · 第 5 章 · 9 次浏览

WXSS 和 CSS 几乎一样,多了 rpx 单位(适配屏幕)和少量扩展。rpx 是小程序特色:750rpx = 屏幕宽度,自动适配不同手机。

单位

rpx 响应式像素,设计稿按 750 宽做,写多少就是多少 rpx;px 固定像素;百分比和 vw/vh 也能用。

样式导入

@import "common.wxss"; 引入公共样式。app.wxss 全局生效。

flex 布局

display: flex 是最常用的布局方式,横向排列、居中、换行都靠它。

代码示例

/* pages/index/index.wxss */
.container {
  padding: 32rpx;
  background: #f5f5f5;
  min-height: 100vh;
}

.title {
  font-size: 40rpx;
  font-weight: bold;
  color: #33691e;
  display: block;
  margin-bottom: 24rpx;
}

.item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
  padding: 24rpx;
  border-radius: 16rpx;
  margin-bottom: 16rpx;
}

.price {
  color: #e53935;
  font-size: 32rpx;
  font-weight: bold;
}

/* 导入公共样式 */
/* @import "common.wxss"; */
📚 CSS 属性速查
常用条目速查,完整版见对应教程章节。可复制代码到在线运行中测试。
写法 / 语法作用
color: #333;文字颜色
background: #fff;背景色 / 背景图
font-size: 16px;字号
font-family: Arial;字体
font-weight: bold;字重(加粗)
margin: 10px;外边距(上右下左)
padding: 10px;内边距
border: 1px solid #ccc;边框:粗细 样式 颜色
border-radius: 8px;圆角
width: 100%;宽度
height: 200px;高度
display: flex;弹性布局(现代布局主力)
display: none;隐藏元素
position: relative / absolute / fixed;定位方式
top / left / right / bottom定位偏移
text-align: center;文字水平对齐
line-height: 1.6;行高
overflow: hidden;内容溢出处理
box-shadow: 0 2px 8px rgba(0,0,0,.1);阴影
transition: all .3s;过渡动画
cursor: pointer;鼠标手型
z-index: 10;层叠顺序
max-width: 1200px; margin: 0 auto;容器居中(经典写法)
@media (max-width: 768px) {}响应式断点
:hover鼠标悬停状态