【问题标题】:Center an icon and text with flex-box使用 flex-box 将图标和文本居中
【发布时间】:2016-05-05 01:54:05
【问题描述】:

我在使用 flex-box 在容器中布局某些控件时遇到问题。

我认为这不是 flex-box 问题,而是我的问题是要理解为什么绿色方块在底部有这个额外的高度,而文本和数字同样在顶部。

它应该在中间居中,但是他们从哪里得到这个额外的高度,干扰了居中:

.fd-square-symbol::before {
  content: '';
  position: relative;
  display: inline-block;
  background-color: #98A92A;
  width: 16px;
  height: 16px;
  outline: 1px dashed red;
  vertical-align: top;
}
.fd-input-group {
  display: flex;
  align-items: center;
  outline: 1px dashed red;
}
.fd-input-group__marker {
  margin-right: 5px;
  outline: 1px dashed blue;
}
.fd-input-group__number {
  font-weight: bold;
  outline: 1px dashed red;
}
.fd-input-group__label-column {
  display: flex;
  justify-content: space-between;
  align-items: center;
  position: relative;
  outline: 1px dashed red;
}
.fd-input-group__label-column-label {
  outline: 1px dashed red;
}
.fd-info-button {
  min-width: 20px;
  height: 10px;
  outline: 1px dashed red;
}
.fd-input-group__control-column {
  display: inline-block;
  flex-grow: 1;
  outline: 1px dashed red;
}
<div class="fd-input-group">
  <div class="fd-input-group__label-column">
    <div>
      <span class="fd-input-group__marker fd-square-symbol"></span>
      <span class="fd-input-group__number">3.14</span>
      <label class="fd-input-group__label-column-label">A question</label>
    </div>
    <button type="button" class="fd-info-button"></button>
  </div>
  <div class="fd-input-group__control-column">
    <input type="text" value="a value" />
  </div>
</div>

JSBin

【问题讨论】:

  • 尝试将 vertical-align:top 添加到绿色方块? jsbin.com/qelafa/4/edit?css,output
  • @Rachel S:它做了一些看起来正确的事情。但是为什么会有额外的高度,为什么你的建议也会影响文本?

标签: html css flexbox


【解决方案1】:

行上的对象不是弹性项目。它们是块容器的子级,因为它们的父级是基本的div,默认为display: block

要让子项成为弹性项目,div 需要为 display: flexdisplay: inline-flex

绿色框底部有一个间隙的原因是因为它是一个inline-block 元素。与所有内联元素一样,浏览器会增加空间以容纳下行元素。

这个下降空间将绿色盒子向上推,这增加了 div 的高度,从而导致了与其他元素之间的间隙。

vertical-align: bottom 应用于绿色框元素以解决问题。

请在此处查看我的答案以获取更多详细信息:https://stackoverflow.com/a/36975280/3597276

【讨论】:

    猜你喜欢
    • 2016-07-23
    • 2019-03-12
    • 2021-10-07
    • 2022-11-11
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 2013-04-14
    • 2021-11-09
    相关资源
    最近更新 更多