如何通过HTML/CSS缩小表格行间距,拉近黄色信息与标题距离?
解决表格行间距过大及元素重叠的实现方案
问题背景
需要缩小表格行间距,让黄色信息区域(<fieldset>部分)与上方标题更贴近,尝试负margin无效,也可接受元素重叠的实现方式。
现有代码片段
HTML结构
<div class="visible-mobile"> <div class="header-panel-mobile" cellpadding = "0" cellspacing = "0" style=" height: 50vw; width: 85vw; margin-right: auto; margin-left: auto;background-color: #eaeaea;border-radius: 10px;"> <table class="header-table-mobile" style="border-collapse: collapse; border-spacing: 0;"> <tr> <td class="font-roboto font-12 " style="padding-top: 3vw; text-align: center; width: 1vw; color:#4d4c4c; font-weight: 900"> <legend class="legend font-roboto font-12" style="width: 100%">{% trans %}alert_level_caps{% endtrans %}</legend> </td> </tr> <!-- SEPARADOR HORIZONTAL --> <tr> <td class=""> <hr style="height: 0.015vh; width:7%; border-width: 0; color: #f7a800; background-color: #f7a800; margin-right: auto; margin-left: auto"> </td> </tr> <!-- BARRA NIVEL DE ALERTA --> <tr> <td class="" style="width: 100%; height: 6%; text-align: center; vertical-align: top"> <!-- FIELDSET NIVEL DE ALERTA --> <fieldset id="barra-dispositivo-movil" class="fieldsetGris centeredFieldset font-roboto font-12" style="height: 2vw; width: 40vw; display: flex; justify-content: center; align-items: center; margin-right: auto; margin-left: auto; border-radius: 10px;"> <!-- TEXTO ALERTA --> <div id="" class="" style=""> <p id="textAlarm" class="" style="color:#FFFFFF">--</p> </div> </fieldset> </td> </tr>
CSS样式
.header-table-mobile { width: 100%; margin: 0 0; margin-top: 0; }
具体解决方法
方法一:彻底缩小行间距(无重叠)
控制表格行与单元格的间距
给表格行设置极小的行高,同时清除单元格默认上下内边距:.header-table-mobile tr { line-height: 0; } .header-table-mobile td { padding-top: 0 !important; padding-bottom: 0 !important; }若标题需要保留顶部间距,单独给标题所在
<td>设置padding-top: 3vw即可。调整分隔线
<hr>的外边距
给<hr>设置负的上外边距,让它向上贴近标题:<hr style="...; margin: -1vw auto 0 auto;">微调告警栏的顶部间距
给告警栏所在单元格设置极小的顶部内边距:.header-table-mobile tr:last-child td { padding-top: 0.5vw !important; }
方法二:元素重叠实现(直接让告警栏上移)
如果上述方法达不到预期,用相对定位强制调整位置:
给告警栏所在
<tr>或<fieldset>添加相对定位,设置负的top值实现上移:<tr style="position: relative; top: -2vw;">或直接给
<fieldset>设置:<fieldset id="barra-dispositivo-movil" style="...; position: relative; top: -3vw;">调整
top的负值大小,直到达到理想的重叠效果。若担心标题被遮挡,给标题所在行设置层级:
<tr style="position: relative; z-index: 1;"> <td class="font-roboto font-12 " style="..."> <legend>...</legend> </td> </tr>
内容的提问来源于stack exchange,提问作者adrian
相关产品推荐
相关产品推荐

