如何在文本元素之间添加水平线

问题描述

我试图在两个文本元素之间添加一条线,例如下面的HTML图片,但是我不能。我只能在“培训计划”之间添加一行,其他文本将在下一行。

h3 {
    position: relative;
}

h3 span {
    background-color: white;
    padding-right: 10px;
}

h3:before {
    content:"";
    position: absolute;
    bottom: 0;
    left: 0;
    right: 0;
    height: 0.5em;
    width: 60%;
    border-top: 1px solid black;
    z-index: -1;
}
<h3 style="font-family:Montserrat"><span>Training program</span></h3>
<h3 style="font-family:Montserrat; text-align:right; margin-top:10px"><span>Read more</span></h3>

我想添加一条像这样的图片。有人可以帮我吗?

enter image description here

解决方法

您可以使用flexbox轻松做到这一点。

h3{
  font-family:Montserrat
}
.flex-parent{display:flex;}
.line-div{
  flex: 1; /* flex-grow */
  padding: 0 5px;
}
.the-line{
  height: 50%;
  border-bottom:1px solid #bbb;
}
<div class="flex-parent">
  <h3><span>Training program</span></h3>
  <div class="line-div"><div class="the-line"></div></div>
  <h3><span>Read more</span></h3>
</div>

参考文献:

Excellent flexbox cheatsheet

Excellenter short Video Tutorial

,

您可以使用 flexbox 实现这一目标,您只需要多玩一些。

但这是一个简短的摘要:

.flex {
  display: flex;
  align-items: center;
}

h3 {
  font-family:Montserrat;
}

.line {
  height: 0;
  margin: 0 10px;
  border-top: 1px solid black;
  width: 40%;

}
<div class="flex">
  <h3>Training program</h3>
  <div class="line"></div>
  <h3><span>Read more</span></h3>
</div>

,

有多种方法可以实现此效果,但是一种方法是将两个<h3>元素包含在<div>中,然后将border-bottom应用于其中。

然后,当您将标题推到比通常显示的标题更低的位置(使用垂直平移transform: translateY()),border-bottom现在似乎在两个标题之间运行,而不是在它们下方运行。

工作示例:

.heading-group {
display: flow-root;
border-bottom: 1px solid rgb(191,191,191);
}

.heading {
 padding: 0 6px;
 background-color: rgb(255,255,255);
 transform: translateY(27px);
}

.training {
 float: left;
}

.read-more {
 float: right;
}
<div class="heading-group">
<h3 class="heading training">Training program</h3>
<h3 class="heading read-more">Read more</h3>
</div>

,

您可以使用hr标签在HTML文本之间放置水平行。