
前端开发:巧妙解决同一行相邻列高度差异
在前端布局中,同一行内相邻列高度不一致是常见问题,尤其在使用组件库(如Element UI)时。本文分析问题根源,并提供有效解决方案。
问题描述
假设使用Element UI的el-row和el-col组件,HTML结构如下:
上平行度 平行度OK/NG
对应的CSS代码:
.row {
border-bottom: solid .0625rem #9c9c9c;
display: flex;
align-items: center;
justify-content: center;
.col {
height: 100%;
display: flex;
span:not(:last-child){
border-right: solid .0625rem #9c9c9c;
}
::v-deep span {
flex: 1;
height: 100%;
word-break: break-all;
word-wrap: break-word;
height: 23px;
line-height: 23px;
}
.label{
background-color: #e0e0e0;
color: #000000;
font-weight: bold;
height:auto;
}
.value{
height: auto;
}
}
}
当列内容长度不同时,高度会不一致。
立即学习“前端免费学习笔记(深入)”;
问题分析
问题在于align-items: center;和el-col的高度设置。align-items: center;使列垂直居中,但不同高度的列无法等高。col的height: 100%;限制了其高度,导致内容撑开高度时,其他列高度不变。
解决方案
解决方法如下:
-
调整
align-items属性: 将align-items: center;改为align-items: stretch;,使列高度充满容器。 (实际上恢复默认值即可) -
移除
col的固定高度: 删除col的height: 100%;,让列高度自适应内容。 -
内容居中处理: 由于内容高度自适应后,内容可能不再居中,需要为
.label添加display: flex;和align-items: center;实现垂直居中。
修改后的CSS代码:
.row {
border-bottom: solid .0625rem #9c9c9c;
display: flex;
align-items: stretch; /* 修改此处 */
justify-content: center;
.col {
display: flex;
span:not(:last-child){
border-right: solid .0625rem #9c9c9c;
}
::v-deep span {
flex: 1;
word-break: break-all;
word-wrap: break-word;
height: 23px;
line-height: 23px;
}
.label{
background-color: #e0e0e0;
color: #000000;
font-weight: bold;
height:auto;
display: flex; /* 添加此处 */
align-items: center; /* 添加此处 */
}
.value{
height: auto;
}
}
}
通过以上调整,即可解决同一行相邻列高度不一致的问题,实现列高度统一和内容居中。










