CSS实现table固定宽度,超过单元格部分内容省略

<table>单元格的宽度是根据内容的大小自适应的,没有内容的地方就挤到了一起。需要固定表格宽度和每一列的宽度。

table-layout:fixed

在固定表格布局中,水平布局仅取决于表格宽度、列宽度、表格边框宽度、单元格间距,而与单元格的内容无关。

white-space: nowrap; text-overflow: ellipsis; overflow: hidden;

超过指定长度的文本以省略号的形式显示。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>test</title>
<style>
* {
    padding: 0;
    margin: 0;
}
table {
    width: 300px;
    table-layout:fixed;
}
.first_col {
    white-space: nowrap; text-overflow: ellipsis; overflow: hidden;
    width: 150px;
}
.first_col_text {
    white-space: nowrap; text-overflow: ellipsis; overflow: hidden;
    display: inline-block;
    color: red;
    width: 120px;
}
img {
    width: 20px;
    height: 20px;
    margin-right: 5px;
}
.second_col {
    white-space: nowrap; text-overflow: ellipsis; overflow: hidden;    
    width: 100px;
}
.third_col{
    white-space: nowrap; text-overflow: ellipsis; overflow: hidden;
    width: 50px;
}
</style>
</head>
<body>
<table border="1" cellspacing="0" cellpadding="0">
  <tr>
    <td class="first_col">
        <span class="first_col_text">123456789012345</span>
        <img src="http://tb2.bdstatic.com/tb/editor/images/face/i_f23.png?t=20131111">
    </td>
    <td class="second_col">12345678901234567890123456789012345678901234567890</td>
    <td class="third_col">1</td>
  </tr>
  <tr>
    <td class="first_col"></td>
    <td class="second_col"></td>
    <td class="third_col">12345678901234567890123456789012345678901234567890123456789012345678901234567890</td>
  </tr>
  <tr>
    <td class="first_col">123456789012345</td>
    <td class="second_col"></td>
    <td class="third_col"></td>
  </tr>
</table>
</body>
</html>

 显示效果:

原文地址:https://www.cnblogs.com/wenruo/p/7641425.html