【问题标题】:How to vertically align inline-block elements based on a specific line, ignoring other lines?如何根据特定行垂直对齐 inline-block 元素,忽略其他行?
【发布时间】:2014-09-28 16:49:23
【问题描述】:

我有几个表单字段,每个字段都在一个父 display: inline-block 元素中。字段可以在其中的控件之前或之后有其他元素:

.Field {
  display: inline-block;
  border: solid 1px silver;
  width: 100px;
  padding: 2px;
  margin: 2px;
  vertical-align:middle;
  color:gray;
}
.Control {
  color:black;
  border: solid 1px navy;
  background-color:#def;
  padding:2px;
}
<div class="Field">
  Some text before the line.
  <div class="Control">This</div>
</div>

<div class="Field">
  <div class="Control">should</div>
  Some text after the line.
</div>

<div class="Field">
  <div class="Control">be</div>
</div>

<div class="Field">
  Some text before...
  <div class="Control">neatly</div>
  ...and some text after. Maybe even an image.
</div>

<div class="Field">
  is it possible?
  <div class="Control">aligned</div>
</div>

我正在尝试让vertical-align 工作,以使字段中的“主要”(.Control) 元素彼此相邻。
每个.Field 的基线应由其.Control 确定。

手动指定line-height 不是一个选项,并且周围的文本不应该有零高度或position: absolution:周围的文本应该仍然可见,并影响字段的高度。

这可以通过 CSS 实现吗?

【问题讨论】:

  • 另外一个小补充 - 如果Control 也可能有多行,我们希望通过它的第一行对齐:jsfiddle.net/anmggL1t/1。已添加.Control {display: inline-block; box-sizing: border-box; vertical-align:text-top; width:100%;}

标签: html vertical-alignment css


【解决方案1】:

你需要对你的标记做一个小的调整,把控制元素后面的文本放到span元素中。

然后从 .Field div 中删除 vertical-align:middle,并添加 .Control + span { display:table-cell } 以在垂直对齐评估中隐藏控件元素之后的文本。

这给了你:

.Field {
  display: inline-block;
  border: solid 1px silver;
  width: 100px;
  padding: 2px;
  margin: 2px;
  color:gray;
}
.Control {
  color:black;
  border: solid 1px navy;
  background-color:#def;
  padding:2px;
}

.Control + span {
  display: table-cell;
}
<div class="Field">
  Some text before the line.
  <div class="Control">This</div>
</div>

<div class="Field">
  <div class="Control">should</div>
  <span>Some text after the line.</span>
</div>

<div class="Field">
  <div class="Control">be</div>
</div>

<div class="Field">
  Some text before...
  <div class="Control">neatly</div>
  <span>...and some text after. Maybe even an image.</span>
</div>

<div class="Field">
  is it possible?
  <div class="Control">aligned</div>
</div>

【讨论】:

  • 谢谢,效果很好!我可能还会在控件之前为文本添加一个spanjsfiddle.net/anmggL1t。这看起来正是我所需要的......这种方法有缺点吗?使用table-cell有效吗?无论如何,再次感谢!
  • 这里使用table-cell绝对有效。我想任何方法都有缺点,但没有什么特别的东西会立即浮现在脑海中。
【解决方案2】:

我认为这不可能与您的限制有关,但一个可靠的方法是使用 :before 和 :after 伪选择器。但这并不是真正可维护的,因为突出显示的文本上方或下方的每个内容都应该是绝对位置,并且在 CSS 的“内容”属性内……Hacky 的东西。

如果没有绝对定位,您将无法实现此类操作。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-12-28
    • 1970-01-01
    • 2014-10-19
    • 1970-01-01
    • 2023-03-09
    • 2015-10-07
    • 1970-01-01
    • 2012-10-08
    相关资源
    最近更新 更多