这种效果通常是通过CSS的伪元素::before::after来实现的。具体实现过程如下:

  1. 首先需要为该文字元素添加一个包裹容器,比如一个<span>标签。

  2. 为该容器添加CSS样式position: relative;,将其定位为相对定位。

  3. 为该容器添加CSS样式display: inline-block;,让其可以设置宽度和高度。

  4. 为该容器添加CSS样式padding: 0 10px;,让其左右留出一定的空隙。

  5. 为该容器添加CSS样式border-bottom: 2px solid #000;,设置下横线的样式。

  6. 为该容器添加CSS样式overflow: hidden;,将其内部溢出的内容隐藏起来。

  7. 为该容器添加伪元素::before::after,分别用来添加左侧和右侧的竖线。

  8. 为伪元素::before::after添加CSS样式content: '';,表示伪元素没有实际内容。

  9. 为伪元素::before::after添加CSS样式position: absolute;,将其定位为绝对定位。

  10. 为伪元素::before::after添加CSS样式top: 50%;,将其定位在容器的中央位置。

  11. 为伪元素::before::after添加CSS样式transform: translateY(-50%);,将其垂直居中。

  12. 为伪元素::before::after添加CSS样式height: 2px;,设置竖线的高度。

  13. 为伪元素::before添加CSS样式left: 0;,设置左侧竖线的位置。

  14. 为伪元素::after添加CSS样式right: 0;,设置右侧竖线的位置。

示例代码如下:

HTML代码:

<span class="text-line">这是一段带横线的文字</span>

CSS代码:

.text-line {
  position: relative;
  display: inline-block;
  padding: 0 10px;
  border-bottom: 2px solid #000;
  overflow: hidden;
}

.text-line::before,
.text-line::after {
  content: '';
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  height: 2px;
}

.text-line::before {
  left: 0;
  width: 20px;
  background-color: #000;
}

.text-line::after {
  right: 0;
  width: 20px;
  background-color: #000;
}
``
前端开发中 一段文字两边有横线是怎么样实现的

原文地址: https://www.cveoy.top/t/topic/hiut 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录