表格跨列行中实现两个Label分别左对齐、居中且互不干扰
问题原因
给新Label设置float:left后,浮动元素会脱离普通文档流,但行内内容会自动环绕浮动元素排布,此时原有Label的居中计算范围是浮动元素右侧的剩余空间,并非整行的完整宽度,因此会被挤向右侧,无法保持在跨列行的正中间位置。
实现方案
采用绝对定位放置左对齐新标签的方案,完全不干扰原有居中标签的布局计算:
- 给跨6列的底部单元格设置
position: relative,作为内部绝对定位元素的参照容器 - 移除新Label上的
float:left属性,改为设置position: absolute,配合left属性控制左对齐边距,数值和单元格的padding值保持一致即可,保证和单元格内边距对齐 - 给底部单元格添加
text-align: center属性,原有Label无需额外设置样式即可保持居中——因为绝对定位的新标签完全脱离文档流,不占用普通排布空间,原有Label的居中计算会基于整个单元格的完整宽度,不会出现偏移。
修正后完整代码
<table> <tr> <td style="border:solid; border-color:black; background-color:#e0e0eb;"> <asp:Label ID="Label1" runat="server" Font-Bold="false"></asp:Label> </td> <td style="border:solid; border-color:black; background-color:#e0e0eb;"> <asp:Label ID="Label2" runat="server" Font-Bold="false"></asp:Label> </td> <td style="border:solid; border-color:black; background-color:#e0e0eb;"> <asp:Label ID="Label3" runat="server" Font-Bold="false"></asp:Label> </td> <td style="border:solid; border-color:black; background-color:#e0e0eb;"> <asp:Label ID="label4" runat="server" Font-Bold="false"></asp:Label> </td> <td style="border:solid; border-color:black; background-color:#e0e0eb;"> <asp:Label ID="label5" runat="server" Font-Bold="false"></asp:Label> </td> <td style="border:solid; border-color:black; background-color:#e0e0eb;"> <asp:Label ID="Label6" runat="server" Font-Bold="false"></asp:Label> </td> </tr> <tr> <td colspan="6" style="position: relative; border:solid; border-color:black; padding:10px; background-color:#99ccff; text-align:center;"> <asp:Label ID="NewLabel" runat="server" Font-Bold="false" Style="position:absolute; left:10px;"></asp:Label> <asp:Label ID="OriginalLabel" runat="server" Font-Bold="false"></asp:Label> </td> </tr> </table>
补充:如果后续需要在该行添加右对齐元素,同理设置
position: absolute; right:10px;即可,同样不会影响中间原有Label的居中效果。
内容的提问来源于stack exchange,提问作者Marc.Heidemann
相关产品推荐
相关产品推荐

