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

标签 html css

我正在尝试在垂直线之前和之后向文本字段添加伪造的样式目的。这些元素需要与文本齐平 -20px 左侧和 -20px 右侧。

当文本作为行内 block 在一行上时,这工作正常,但一旦文本跨越多行,宽度就会扩展到父元素的宽度,并且伪元素不再距离文本只有 20px。

有没有一种方法可以使用 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 中删除它们,并添加一个新的 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

关于html - 将伪类 "before"和 "after"应用于多行文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52161414/

相关文章:

css - Vaadin 使用 CSS 在 v.tabsheet 中分隔标签

html - 如何将状态文本颜色更改为按钮

javascript - 是否可以使用所选文件创建文件输入

javascript - 为什么按下 Alt 键时会引发 html input onBlur 事件?

html - 使用内联 css 强制容器获取 child 的高度

css - 我在居中时遇到问题......再次

CSS 未应用于 jinja2 模板

html - Bootstrap 3 站点布局图像网格

html - 在背景图像上使用前后伪元素

html - 为什么我的 CSS 边框没有出现在按钮周围的范围内?