Html 如何在 MVC 视图中设置表格列宽?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12074901/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 02:25:31  来源:igfitidea点击:

How can I set table column widths in an MVC view?

htmlcssasp.net-mvcasp.net-mvc-4

提问by ProfK

I am using the default, design-time scaffolded view for a list, in an MVC4 Razor app. Each column is as follows:

我在 MVC4 Razor 应用程序中使用列表的默认设计时脚手架视图。每列如下:

<td class="col-code">
    @Html.DisplayFor(modelItem => item.Code)
</td>

I have tried adding a widthattribute to the TD's, but seems to have no effect. The only thing that works is styling the INPUT rendered by DisplayFor, but I can't do that here as I have nowhere to set html attributes.

我曾尝试向widthTD添加一个属性,但似乎没有效果。唯一有效的方法是DisplayFor设置 .

回答by Yannick Blondeau

If you are using simple HTML tables, you should add a header to your columns using the thtag that can then be styled to the desired width.

如果您使用简单的 HTML 表格,您应该使用th标签向列添加标题,然后可以将其样式设置为所需的宽度。

For example:

例如:

<table>
  <tr>
    <th class="col1">First col</th>
    <th class="col2">Second col</th>
  </tr>
  <tr>
    <td>First cell</td>
    <td>Second cell</td>
  </tr>
  <tr>
    <td>Third cell</td>
    <td>Fourth cell</td>
  </tr>
</table>

can be used with this CSS code:

可以与此 CSS 代码一起使用:

.col1 {
    width: 75%;
}

.col2 {
    width: 25%; /* not very useful in this case as 'col2' will take the remaining */
}

回答by smac2020

You can use this as well in a view:

您也可以在视图中使用它:

**@model List<Student>
@{
    ViewData["Title"] = "Index"; }
<h2>NEW VIEW Index</h2>
<table class="table">
    <tr>
        <th scope="col">
         ID          </th>
        <th scope="col">
            FirstName
        </th>
        <th scope="col">
            LastName
        </th>
     </tr>
     @foreach (var element in Model) {
    <tr>    <td>@Html.DisplayFor(m => element.ID)</td>  <td>@Html.DisplayFor(m => element.FirstName)</td>   <td>@Html.DisplayFor(m => element.LastName)</td>    </tr>
}
    </table>**  

The result is nice:

结果很好:

enter image description here

在此处输入图片说明