CSS文本
2023-08-22 16:47:25 #CSS

文本溢出

  • 单行文字溢出显示省略号
1
2
3
4
5
6
.container {
overflow: hidden;
-ms-text-overflow: ellipsis;
text-overflow: ellipsis;
white-space: nowrap;
}
  • 多行文字溢出显示省略号
1
2
3
4
5
6
7
8
.container {
display: -webkit-box; /* 将对象作为弹性伸缩盒子模型显示 */
-webkit-line-clamp: 3; /* 限制在一个块元素显示的文本的行数 */
-webkit-box-orient: vertical; /* 设置或检索伸缩盒对象的子元素的排列方式 */
overflow: hidden;
-ms-text-overflow: ellipsis;
text-overflow: ellipsis;
}
image-20230822153315702

文本换行

  • 如果行内没有多余的地方容纳该单词到结尾,则那些正常的不能被分割的单词会被强制分割换行
1
2
3
.container {
overflow-wrap: break-word;
}
  • 对于非 CJK 文本,在任意字符间断行
1
2
3
.container {
word-break: break-all;
}
image-20230822153356897

line-height 继承

1
2
3
<body>
<p>这是一段文字</p>
</body>
  • 具体数值:子元素未设置具体行高数值,会自动继承父元素的行高
1
2
3
4
5
6
7
8
9
/* p的line-height是50px */
body {
font-size: 20px;
line-height: 50px;
}
p {
background-color: #ccc;
font-size: 16px;
}
  • 按比例:子元素未设置行高,父元素行高为1.5,子元素 line-height = 自身 font-size * 1.5
1
2
3
4
5
6
7
8
9
/* p的line-height是24px */
body {
font-size: 20px;
line-height: 1.5;
}
p {
background-color: #ccc;
font-size: 16px;
}
  • 百分比:子元素不会直接继承父元素行高,而是继承父元素字体大小 * 行高百分比
1
2
3
4
5
6
7
8
9
/* p的line-height是40px */
body {
font-size: 20px;
line-height: 200%;
}
p {
background-color: #ccc;
font-size: 16px;
}