内联块元素与省略号溢出不垂直对齐

4

我正在将 labelinputdiv 元素行内显示,期望它们垂直对齐,并且最初是可以的。

但是,当我尝试使用省略号让 div 内容溢出时,它们不再垂直对齐了。

注意: 这在 Chrome 46.02490.86 中被观察到。

p {color:red;}
input,
label,
div {
  width: 50px;
  display: inline-block;
  margin-left: 5px;
}
label {
  text-align: right;
}
.longdesc {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
 
<label>Name:</label>
<input type='text' value='James'>
<label>Desc:</label>
<div>Short</div>
<hr />
<label>Name:</label>
<input type='text' value='James'>
<label>Desc:</label>
<div class='longdesc'>Longer Description</div>
<p>
    In the second example "Long" is higher up
</p>

如何实现溢出效果而不影响垂直对齐?

1
垂直对齐不是上下吗?水平对齐是左右吧? inline-block 是为了将元素从左到右显示。 block 是为了将元素垂直地排列在一起(换句话说,堆叠在彼此上方)。我明白了,您想要内容对齐,好的。 - zer00ne
我所说的垂直对齐是指将文本放在同一行内,没有上下偏移。也许我的用词不太准确。 - Eric Phillips
2个回答

10
在你的 inline-block 元素上添加 vertical-align: top

p {color:red;}
input,
label,
div {
  width: 50px;
  display: inline-block;
  margin-left: 5px;
  vertical-align: top;
}
label {
  text-align: right;
}
.longdesc {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
 
<label>Name:</label>
<input type='text' value='James'>
<label>Desc:</label>
<div>Short</div>
<hr />
<label>Name:</label>
<input type='text' value='James'>
<label>Desc:</label>
<div class='longdesc'>Longer Description</div>
<p>
    In the second example "Long" is higher up
</p>


谢谢,我会接受这个答案。奇怪的是,vertical-align: top, middle, bottom 产生了相同的结果。 - Eric Phillips
1
@EricPhillips - 这是因为你只有一行,所以顶部、中间和底部都是相同的。尝试使用多行来看看区别。 - Amit
1
单行还是元素同高? - Narek-T
2
只需为您的input设置高度(例如100px),即可看到差异。现在,您的所有元素都具有相同的高度约18px。 - Narek-T

2

我不明白在CSS中垂直对齐的位置在哪里? 默认情况下,vertical-align 属性具有 baseline 属性,如果您想要居中,请使用 vertical-align: middle

p {color:red;}
input,
label,
div {
  width: 50px;
  display: inline-block;
  margin-left: 5px;
  vertical-align: middle;
}
label {
  text-align: right;
}
.longdesc {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}
 
<label>Name:</label>
<input type='text' value='James'>
<label>Desc:</label>
<div>Short</div>
<hr />
<label>Name:</label>
<input type='text' value='James'>
<label>Desc:</label>
<div class='longdesc'>Longer Description</div>
<p>
    In the second example "Long" is not higher up :)
</p>


没错,我没有具体说明,因为我没有预料到在实现溢出省略代码块之前需要定义垂直对齐。 - Eric Phillips

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接