css 一条横线中间加文字
秀秀 发布于 2024-6-7 15:25 20 次阅读
要在一条水平线的中间添加文字,可以使用 ::before
和 ::after
伪元素,并结合 display: flex
布局。这样可以确保线条和文字在视觉上保持一致。以下是一个示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Line with Text</title>
<style>
.line-container {
display: flex;
align-items: center;
width: 100%;
}
.line {
flex: 1;
height: 1px;
background: #000;
}
.line-text {
padding: 0 10px;
color: #000;
white-space: nowrap;
}
.line-container::before,
.line-container::after {
content: '';
flex: 1;
height: 1px;
background: #000;
}
</style>
</head>
<body>
<div class="line-container">
<span class="line-text">Your Text Here</span>
</div>
</body>
</html>
解释:
-
容器 (
.line-container
):- 使用
display: flex
和align-items: center
让内容垂直居中。
- 使用
-
伪元素 (
::before
和::after
):content: '';
创建一个空的伪元素。flex: 1;
让伪元素占据容器的剩余空间。height: 1px;
设置线条的高度。background: #000;
设置线条的颜色。
-
文字 (
.line-text
):padding: 0 10px;
为文字两侧添加一些内边距,以确保文字不会贴在线条上。white-space: nowrap;
确保文字不会因为过长而换行。
这个方法将文字置于水平线的中间,两侧的线条长度会根据容器的宽度自动调整。