uniapp 2列布局
uniapp 实现 2 列布局的方法
使用 Flex 布局
Flex 布局是最常用的方法之一,可以轻松实现两列布局。通过设置 display: flex 和 flex-wrap: wrap,子元素会自动排列成两列。
<template>
<view class="container">
<view class="item" v-for="(item, index) in list" :key="index">
{{ item }}
</view>
</view>
</template>
<style>
.container {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
}
.item {
width: 48%;
margin-bottom: 10px;
background-color: #f0f0f0;
padding: 10px;
box-sizing: border-box;
}
</style>
使用 Grid 布局
CSS Grid 布局提供了更灵活的网格系统,适合复杂的布局需求。通过 display: grid 和 grid-template-columns 可以定义两列。
<template>
<view class="grid-container">
<view class="grid-item" v-for="(item, index) in list" :key="index">
{{ item }}
</view>
</view>
</template>
<style>
.grid-container {
display: grid;
grid-template-columns: repeat(2, 1fr);
gap: 10px;
}
.grid-item {
background-color: #f0f0f0;
padding: 10px;
}
</style>
使用百分比宽度
通过设置子元素的宽度为 50% 或 49%(留出间距),可以实现简单的两列布局。
<template>
<view class="percent-container">
<view class="percent-item" v-for="(item, index) in list" :key="index">
{{ item }}
</view>
</view>
</template>
<style>
.percent-container {
width: 100%;
}
.percent-item {
width: 49%;
float: left;
margin-right: 2%;
margin-bottom: 10px;
background-color: #f0f0f0;
padding: 10px;
box-sizing: border-box;
}
.percent-item:nth-child(2n) {
margin-right: 0;
}
</style>
使用 uni-row 和 uni-col 组件
uniapp 提供了 uni-row 和 uni-col 组件,可以快速实现栅格布局。
<template>
<uni-row>
<uni-col span="12" v-for="(item, index) in list" :key="index">
<view class="col-item">
{{ item }}
</view>
</uni-col>
</uni-row>
</template>
<style>
.col-item {
background-color: #f0f0f0;
padding: 10px;
margin: 5px;
}
</style>
注意事项
- 确保父容器宽度足够,避免内容溢出。
- 使用
box-sizing: border-box防止内边距影响布局。 - 在移动端适配时,可以通过媒体查询调整布局。







