【问题标题】:Display flex and any other HTML tag显示 flex 和任何其他 HTML 标签
【发布时间】:2022-01-26 10:19:27
【问题描述】:

假设这个非常简单的案例:

.header-top .custom-html {
  display: flex;
  align-items: center;
}
<div class="header-top header-has-center-sm">
  <div class="header-row container-fluid">
    <div class="header-col header-left hidden-for-sm">
      <div class="custom-html"><i class="porto-icon-shipping me-2" style="font-size: 2em; vertical-align: middle;"></i>Shipping to all states, <span style="font-weight: bold;">FREE</span> shipping to orders above $50</div>
    </div>
    <div class="header-col visible-for-sm header-center">
      <div class="custom-html">&nbsp;</div>
    </div>
    <div class="header-col header-right hidden-for-sm">
      <div class="custom-html"><i class="Simple-Line-Icons-badge me-2" style="font-size: 2em; vertical-align: middle;"></i>All our products are <b>GENUINE</b></div>
    </div>
  </div>
</div>

如您所见,&lt;b&gt; 标签的内容紧挨着周围的单词,就好像它周围没有空格一样。

有人可以解释为什么会发生这种情况以及如何解决吗?这是我第一次注意到这种情况……

基本上,我将内容的显示设置为 flex,因为我需要垂直对齐到文本的中间。但这种副作用是完全出乎意料的......

【问题讨论】:

  • 弹性容器中有三个块:&lt;i&gt;、一个文本节点和&lt;b&gt;。 flex 的子级被视为块。默认情况下,flex 没有间隙。作为一般的 HTML 效果,块的开头和结尾处的空白被折叠为空。
  • 那么有什么办法可以克服这个问题吗?
  • 取决于您要执行的操作。也许添加一个包装器将内部块组合在一起,以便 flex 容器只有一个孩子。
  • 我正在尝试做显而易见的事情:在 flex 中渲染空格!实际上,我只是能够使用white-space: break-spaces; 属性来做到这一点...我不确定这是否是该属性的预期用途,但就我而言,它使事情按预期工作!我去查一下!
  • @MichaelBenjamin 实际上 vertical-align: middleicon 在我需要垂直对齐文本之前,主题就在那里......现在我已经使用了 flex属性align-items: center,确实vertical-align: middle 是多余的,我会完全删除它!感谢您的关注!

标签: css flexbox vertical-alignment


【解决方案1】:

问题在于您的文本分组。我知道这听起来很奇怪,但包含在 div 中的文本并没有真正分组。您需要将其包装在 &lt;span&gt;&lt;p&gt; 标记中。我使用了&lt;span&gt; 只是为了让浏览器知道这个文本属于一起。您可以使用&lt;p&gt; 标签,它显然带有更多预设样式,例如顶部和底部的边距。

.header-top .custom-html {
  display: flex;
  align-items: center;
}
<div class="header-top header-has-center-sm">
  <div class="header-row container-fluid">
    <div class="header-col header-left hidden-for-sm">
      <div class="custom-html"><span><i class="porto-icon-shipping me-2" style="font-size: 2em; vertical-align: middle;"></i>Shipping to all states, <span style="font-weight: bold;">FREE</span> shipping to orders above $50</span>
      </div>
    </div>
    <div class="header-col visible-for-sm header-center">
      <div class="custom-html">&nbsp;</div>
    </div>
    <div class="header-col header-right hidden-for-sm">
      <div class="custom-html"><span><i class="Simple-Line-Icons-badge me-2" style="font-size: 2em; vertical-align: middle;"></i>All our products are <b>GENUINE</b></span></div>
    </div>
  </div>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-03-06
    • 1970-01-01
    • 1970-01-01
    • 2016-09-15
    • 2017-11-08
    • 1970-01-01
    • 2014-10-17
    • 1970-01-01
    相关资源
    最近更新 更多