前言
场景题:有两个span,一个需要做省略处理,另外一个放置固定内容,问这两个span是在同一行中吗?如果不在,为什么,怎么让它们在同一行显示?
为了解决上述问题:我们写了如下代码进行判断
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
* {
padding: 0;
margin: 0;
}
div {
width: 100%;
background-color: bisque;
text-align: center;
}
.span1 {
display: inline-block;
width: 50px;
height: 100px;
line-height: 100px;
background-color: chocolate;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.span2 {
display: inline-block;
height: 100px;
line-height: 100px;
background-color: cadetblue;
}
</style>
</head>
<body>
<div>
<span class="span1">你好星期三</span>
<span class="span2">请前往东京</span>
</div>
</body>
</html>
其中为什么我们要将两个span标签都设置display: inline-block;原因是效果要做省略处理就一定要将其转化为行内块元素或者块元素,这里设置块元素就没有必要了。所以我们还是设置了display: inline-block;
最后的结果为:
我们来分析一下,为什么会出现这种情况?为什么没有按照我们自己的想法来进行呢?
原因是:行内块元素会和文字的基线对齐
我们可以给两个span标签设置
vertical-align: baseline;
我们会发现视图并未发生任何变化。
所以就不怪“请前往京东”这几个字在蓝色线下面还有一些未完成的笔画。
解决:我们可以设置vertical-align
<style>
* {
padding: 0;
margin: 0;
}
div {
width: 100%;
background-color: bisque;
text-align: center;
}
.span1 {
display: inline-block;
width: 50px;
height: 100px;
line-height: 100px;
background-color: chocolate;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
vertical-align: top;
}
.span2 {
display: inline-block;
height: 100px;
line-height: 100px;
background-color: cadetblue;
vertical-align: top;
}
最后的结果为:
其中
vertical-align: top|bottom|middle;
都可以达到相同的效果