未添加样式前:
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
width: 100px;
height: 100px;
background-color: yellow;
margin: 100px auto;
}
</style>
</head>
<body>
<div>
为中华之崛起而读书!!!
</div>
</body>
</html>
运行结果:
如上图,当盒子宽度不够时,文字会自动换行。
那如何让文字用省略号表示呢?
步骤一:让文字强制在一行显示。代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
width: 100px;
height: 100px;
background-color: yellow;
margin: 100px auto;
/* 限制一行内显示文本 */
white-space: nowrap;
}
</style>
</head>
<body>
<div>
为中华之崛起而读书!!!
</div>
</body>
</html>
运行结果如下:
步骤二:让溢出的部分隐藏,代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
width: 100px;
height: 100px;
background-color: yellow;
margin: 100px auto;
/* 限制一行内显示文本 */
white-space: nowrap;
/* 隐藏溢出的部分文字 */
overflow: hidden;
}
</style>
</head>
<body>
<div>
为中华之崛起而读书!!!
</div>
</body>
</html>
运行结果如下:
步骤三:用是省略号代替溢出的部分,代码如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
width: 100px;
height: 100px;
background-color: yellow;
margin: 100px auto;
/* 限制一行内显示文本 */
white-space: nowrap;
/* 隐藏溢出的部分文字 */
overflow: hidden;
/* 溢出部分用省略号表示 */
text-overflow: ellipsis;
}
</style>
</head>
<body>
<div>
为中华之崛起而读书!!!
</div>
</body>
</html>
运行结果如下:
总结:
为了让单行文本溢出的部分用省略号表示,只需添加如下三行代码:
1.white-space:nowrap;
2.overflow:hidden;
3.text-overflow:ellipsis;