Bootstrap响应式表格比较宽时,为适应手机屏幕宽度,会自动对各列进行压缩,内容分多行显示。但像姓名分几行显示效果不好。我们希望表格显示不下时,不改变列宽度,而是出现滚动杆,保持表格原来的外观。
可通过设置white-space: nowrap属性来实现。
CSS 样式代码:
用于禁止格子内换行。
.cell_nowrap {
white-space: nowrap;
}
HTML代码:
<div class="table-responsive">
<table class="table table-bordered cell_nowrap" >
<!-- 表头 -->
<thead>
<tr><th>年级</th><th>学生</th><th>题目</th></tr>
</thead>
<tbody>
<!-- 表格内容 -->
<tr><td>2019</td><td>张小三</td><td>文字不换行在手机上的显示,显示不下时自动出现滚动条</td></tr>
<tr><td>2019</td><td>赵小四</td><td>文字不换行在手机上的显示,显示不下时自动出现滚动条</td></tr>
<tr><td>2019</td><td>王小五</td><td>不会出现姓名栏变窄竖排</td></tr>
</tbody>
</table>
</div>
这里用的是Bootstrap4,类table-responsive、table使表格成为响应式表格,会根据屏幕大小自适应显示。
完整代码如下,可在服务器上运行显示效果。
<html>
<head>
<meta charset="UTF-8" >
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
<title>表格单元内容不换行</title>
<!-- Bootstrap4 CSS -->
<link rel="stylesheet" href="https://cdn.staticfile.org/twitter-bootstrap/4.3.1/css/bootstrap.min.css">
<!-- 自定义样式 -->
<style>
.cell_nowrap {
white-space: nowrap;
}
</style>
</head>
<body>
<div class="container">
<div class="table-responsive">
<table class="table table-bordered cell_nowrap" >
<!-- 表头 -->
<thead>
<tr><th>年级</th><th>学生</th><th>注释</th></tr>
</thead>
<tbody>
<!-- 表格内容 -->
<tr><td>2019</td><td>张小三</td><td>文字不换行在手机上的显示,显示不下时自动出现滚动条</td></tr>
<tr><td>2019</td><td>赵小四</td><td>文字不换行在手机上的显示,显示不下时自动出现滚动条</td></tr>
<tr><td>2019</td><td>王小五</td><td>不会出现姓名栏变窄竖排</td></tr>
</tbody>
</table>
</div>
</div>
</body>
</html>