css - 使用 css 在文本后创建行

标签 css

我试图在我的每个 h2 标签后划一行。我无法弄清楚我应该如何分辨宽度,因为 h2 标题的长度从 h2 到 h2 是不同的。

我使用 :after 方法来创建行

       h2:after {
       position: absolute;
       content: "";
       height: 2px;
       background-color: #242424;
       width: 50%;
       margin-left: 15px;
       top: 50%;
       } 

在这里检查代码:http://jsfiddle.net/s9gHf/ 如您所见,线条变得太宽,使网站变得太宽。

最佳答案

您可以通过额外的 <span> 来实现此目的:

h2 {
  font-size: 1rem;
  position: relative;
}

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

h2:after {
  content: "";
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  height: 0.5em;
  border-top: 1px solid black;
  z-index: -1;
}
<h2><span>Featured products</span></h2>
<h2><span>Here is a very long h2, and as you can see the line get too wide</span></h2>

另一种没有额外的解决方案 <span>但需要 overflow: hidden<h2> 上:

h2 {
  font-size: 1rem;
  overflow: hidden;
}

h2:after {
  content: "";
  display: inline-block;
  height: 0.5em;
  vertical-align: bottom;
  width: 100%;
  margin-right: -100%;
  margin-left: 10px;
  border-top: 1px solid black;
}
<h2><span>Featured products</span></h2>
<h2><span>Here is a very long h2, and as you can see the line get too wide</span></h2>

外部示例:First , Second

关于css - 使用 css 在文本后创建行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20935191/

相关文章:

相当于 "font size+2"的 HTML 样式标签

Chrome 和 IE 中的 CSS 图片悬停问题

javascript - 向 HTML anchor 添加多个操作

html - Bootstrap 4 Flexbox 将屏幕分成 4 部分

javascript - 将div分成方 block

html - CSS 渐变 strip 问题?

css - 需要给元素的边框加上border-radius

css - 循环进度显示超过100%

javascript - Twitter Bootstrap 模式出现在错误的位置,不居中且按钮不可点击

html - z-index 和 CSS 旋转