<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>圆角矩形文本</title>
<style type="text/css">
.box {
width: 200px;
height: 100px;
background-color: green;
border-radius: 20px;
position: relative;
}
.box::before {
content: "";
position: absolute;
width: 2px;
height: 100px;
background-color: brown;
left: 50%;
top: 100%;
}
.text {
position: absolute;
width: 80%;
height: auto;
left: 10%;
top: 50%;
border-radius: 20px;
overflow-wrap: break-word;
text-align: center;
line-height: 1.5;
}
.text::after {
content: "...";
}
</style>
</head>
<body>
<div class="box" id="box">
<div class="text" id="text">这是一个圆角矩形文本,它会自动换行,不会超出圆角矩形的范围,最多换两行,后面用...表示。</div>
</div>
<script type="text/javascript">
// 获取元素
var box = document.getElementById("box");
var text = document.getElementById("text");
// 获取文本的字体大小和行高
var fontSize = parseInt(window.getComputedStyle(text).fontSize);
var lineHeight = parseFloat(window.getComputedStyle(text).lineHeight);
// 计算文本的最大高度
var maxHeight = lineHeight * 2 + fontSize / 2;
// 判断文本是否超过最大高度
if (text.offsetHeight > maxHeight) {
// 设置文本的高度为最大高度
text.style.height = maxHeight + "px";
// 设置文本的溢出隐藏和省略号显示
text.style.overflow = "hidden";
text.style.textOverflow = "ellipsis";
}
// 判断文本是否超过9个字符
if (text.textContent.length > 9) {
// 截取前9个字符并加上省略号
text.textContent = text.textContent.slice(0,9) + "...";
}
// 设置文本的垂直居中
text.style.transform = "translateY(-50%)";
</script>
</body>
</html>
效果图:
、
html在线运行:把代码复制到这里可以看到效果:HTML/CSS/JS 在线工具 | 菜鸟工具
另外一个版本:
<!DOCTYPE html>
<html>
<head>
<style>
.container {
display: flex;
justify-content: center;
}
.lollipop {
position: relative;
}
.stick {
width: 2px;
height: 60px;
background-color: #333;
position: absolute;
bottom: -60px;
left: calc(50% - 1px);
}
.round-rect {
width: 200px;
height: 80px;
border-radius: 40px;
background-color: #333;
}
.text {
color: #fff;
text-align: center;
line-height: 80px;
}
</style>
</head>
<body>
<div class="container">
<div class="lollipop">
<div class="stick"></div>
<div class="round-rect">
<span class="text">这是一段文字</span>
</div>
</div>
</div>
</body>
</html>