在UniApp中实现电脑网页table的自适应布局,可以通过以下方法:
1. 使用百分比宽度
.table {
width: 100%;
}
.table th,
.table td {
width: 25%; /* 根据列数调整百分比 */
}
2. 使用Flex布局
.table-container {
display: flex;
flex-direction: column;
}
.table-row {
display: flex;
}
.table-cell {
flex: 1;
min-width: 0; /* 防止内容溢出 */
}
3. 使用Grid布局(推荐)
.table {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(100px, 1fr));
gap: 1px;
}
4. 响应式处理
/* 小屏幕时改为垂直布局 */
@media (max-width: 768px) {
.table {
display: block;
}
.table-row {
display: block;
margin-bottom: 10px;
}
}
5. 表格溢出处理
.table-container {
overflow-x: auto;
white-space: nowrap;
}
完整示例:
<template>
<view class="table-container">
<view class="table">
<view class="table-row header">
<view class="cell">姓名</view>
<view class="cell">年龄</view>
<view class="cell">职业</view>
</view>
<view class="table-row">
<view class="cell">张三</view>
<view class="cell">25</view>
<view class="cell">工程师</view>
</view>
</view>
</view>
</template>
<style scoped>
.table-container {
width: 100%;
overflow-x: auto;
}
.table {
display: grid;
grid-template-columns: repeat(3, 1fr);
min-width: 600px;
}
.table-row {
display: contents;
}
.cell {
padding: 12px;
border: 1px solid #ddd;
text-align: center;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.header .cell {
background-color: #f5f5f5;
font-weight: bold;
}
/* 响应式适配 */
@media (max-width: 768px) {
.table {
grid-template-columns: 1fr;
min-width: unset;
}
}
</style>
关键点:
- 使用Grid布局实现自动列宽分配
- 设置最小宽度防止过度压缩
- 添加水平滚动保证小屏可用性
- 移动端适配时改为垂直布局
这样就能实现table在不同屏幕尺寸下的自适应显示。