将伪类"before"和"after"应用于多行文本

3
我正在尝试为样式目的在文本字段中添加伪前后垂直线。 这些元素需要与文本对齐,距离左侧和右侧各-20像素。
当文本以inline-block的形式显示在一行时,这种做法效果很好,但是一旦文本跨越多行,它的宽度就会扩展到父级的宽度,并且伪元素不再离文本仅有20像素。
是否有一种方法可以使用CSS来实现这个目标?

.container {
  width: 500px;
  background-color: red;
  text-align: center;
  margin-left: 40px;
}

h2 {
  position: relative;
  display: inline-block;
  margin: 0;
  padding: 0;
  background-color: blue;
  color: white;
}

span {
  position: relative;
  background-color: green;
}

h2::before,
h2::after {
  content: '';
  position: absolute;
  top: 0;
  width: 4px;
  height: 20px;
  background: black;
}

h2::before {
  left: -20px;
}

h2::after {
  right: -20px;
}
<!--  Single line example works as the black bars are 20px away from the start/end of text-->
<div class="container">
  <h2><span>This is a title</span></h2>
</div>

<br> <br>

<!--  double line doesn't work because the h2 is now the full width of the container -->
<div class="container">
  <h2><span>This is loooonnggggggggggggggggggggggeeeeerrr</span></h2>
</div>

编辑:以下是使用表格的可用版本,但如果有更好的解决方案,我很想听听:https://codepen.io/anon/pen/MqveLQ


你尝试在 h2:beforeh2:after 上使用 height: 100%; 吗? - fen1x
你能使用对齐文本吗?比如在<h2>中使用空格来填充剩余的空间? - Jack Bashford
@JBDouble05 不是的 - Ryan
也许添加一张您正在尝试的图片会有所帮助。 - Roko C. Buljan
@JBDouble05 我们有设计要求,所以我们无法调整文本。 - Ryan
显示剩余4条评论
2个回答

0

我已将您的代码移动到此fiddle:https://jsfiddle.net/n2Lr6xy5/13/,并删除了position: absolute以及剥离了一些其他似乎不必要的样式,我认为我已经创建了您想要的内容。

这是更新后的CSS:

.container {
  width: 500px;
  background-color: red;
  text-align: center;
  margin-left: 40px;
}


h2{
  display: inline-block;
}

h2:after,
h2:before {
  content: "";
  width: 4px;
  height: 20px;
  background: #000000;
  display: inline-block;
  margin: 0 10px;
}

嗨,Neelam,感谢您的帮助,但这不是我想要做的。如果您查看我的原始示例,您会发现单行是正确的,因为我的竖线距离文本有20像素。 多行示例是不正确的,因为竖线现在距离文本有20像素。 - Ryan

0

所以从我看到的情况来看,问题在于您在应用 before 和 after 边框的位置。您需要更改边框应用的位置。将其从 h2 中删除,并添加一个新的 HTML 元素来包装 h2 并在那里应用。

例如:

    <div class="container">
      <div class="headerwrap">
         <h2><span>This is loooonnggggggggggggggggggggggeeeeerrr</span></h2>
      </div>
    </div>

    <div class="container">
      <div class="headerwrap">
        <h2><span>This is a title</span></h2>
      </div>
    </div>

CSS

    .headerwrap::before,
    .headerwrap::after {
       content: '';
       position: absolute;
       top: 0px;
       bottom:0;
       margin:auto;
       width: 4px;
       height: 20px;
       background: black;
     }

     .headerwrap::before {
       left: 10px;
      }

      .headerwrap::after {
        right: 10px;
      }

这是一个可工作的示例:https://codepen.io/FEARtheMoose/pen/VGbJjO?editors=1100#0 编辑:在评论后更改示例 - https://codepen.io/FEARtheMoose/pen/VGbJjO

嗨Moose,感谢您查看它!不幸的是,那不是我想要的(我意识到我的原始帖子可能没有意义,我很难解释!我希望垂直条始终距离文本左右20px,在您的codepen中,无论文本的左侧如何,条始终保持在同一位置。 - Ryan
没问题。不过你有没有考虑将文本分成更多的元素,以获得像我回答中现在添加的编辑结果呢? - Moose

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