You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Bootstrap样式缩小ASP.NET Web Forms的GridView并使其居中

原因说明

Bootstrap 自带的 .table 类默认会给表格设置 width: 100% 属性,所以表格会默认撑满父级容器的宽度。另外你当前代码存在嵌套表格的问题(外层手动写了<table>标签,GridView 渲染后也会生成<table>标签),容易导致样式冲突,建议先移除外层多余的<table>标签。

解决方案

可以用 Bootstrap 自带的工具类快速实现效果,无需额外写复杂 CSS:

方案1:按比例限制表格宽度(适配响应式)

在外层套一个容器,用 w-* 类限制宽度占比,用 mx-auto 实现水平居中:

<!-- w-75 代表宽度为父容器的75%,可按需替换为w-50、w-80等数值 -->
<div class="w-75 mx-auto">
    <asp:GridView   ID="grdTest"  runat="server" GridLines="Horizontal"  CssClass="table table-sm table-bordered table-condensed table-responsive-sm table-hover table-striped" >   
    </asp:GridView>
</div>

如果你用的是 Bootstrap 3,把 mx-auto 替换为 center-block 即可。

方案2:表格宽度适配内容(适合内容较少的场景)

如果希望表格宽度自动贴合内容大小,不需要占满固定比例,给表格加 .w-auto 类后再套居中容器即可:

<div class="mx-auto w-auto">
    <asp:GridView   ID="grdTest"  runat="server" GridLines="Horizontal"  CssClass="table table-sm table-bordered table-condensed table-responsive-sm table-hover table-striped w-auto" >   
    </asp:GridView>
</div>

方案3:自定义固定最大宽度

如果需要指定表格的最大宽度,加少量自定义 CSS 即可:
首先定义自定义样式:

.grid-container {
    max-width: 900px; /* 可根据需求调整数值 */
}

再套用布局:

<div class="grid-container mx-auto">
    <asp:GridView   ID="grdTest"  runat="server" GridLines="Horizontal"  CssClass="table table-sm table-bordered table-condensed table-responsive-sm table-hover table-striped" >   
    </asp:GridView>
</div>

内容的提问来源于stack exchange,提问作者rimi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.04 04:06:02