我试着做一个水平规则,中间有一些文本。 例如:

----------------------------------- 我的标题 -----------------------------

在CSS中有办法做到这一点吗?显然没有“-”号。


当前回答

最短最佳方法:

跨度:之后, 跨度:{之前 内容:“\ 00 a0 \ 00 a0 \ 00 a0 \ 00 a0 \ 00 a0”; 文字修饰:线穿过; } <span>你的文本</span>

其他回答

透明的单元素动态解决方案:

h2 { display:table; /* fit content width*/ margin:20px auto; /* center*/ padding:0 10px; /* control the space between the text and the line */ box-shadow:0 0 0 100px red; /* control the line length and color here */ --s:2px; /* control the line thickness*/ clip-path: polygon(0 0,100% 0, 99% calc(50% - var(--s)/2), 200vmax calc(50% - var(--s)/2), 200vmax calc(50% + var(--s)/2), 99% calc(50% + var(--s)/2), 100% 100%,0 100%, 1px calc(50% + var(--s)/2), -200vmax calc(50% + var(--s)/2), -200vmax calc(50% - var(--s)/2), 1px calc(50% - var(--s)/2)); } body { background: pink; } <h2>a Title here </h2> <h2 style="box-shadow:0 0 0 100vmax blue;">Title</h2> <h2 style="box-shadow:0 0 0 200px green;--s:5px">Another title Title</h2>

这可能有点超出了问题的范围,但我相信这确实有助于其他有类似问题的人。

如果您需要多个单元格,并且不想显式地指定背景颜色,则必须对行的每个部分使用标记。

这允许你使用一个完整的伸缩线来定位元素,例如扩展器

.title-hr { 宽度:100%; vertical-align:中间; 对齐项目:中心; text-align:开始; 显示:flex; } .title-hr >跨度{ 填料:0 0.4em; } .title-hr >。人力资源{ Border-bottom: 1px实心#777; 行高:0.1 em; 保证金:0.34em 0 0.35em; Flex: 1台自动; } .title-hr > .hr。修复{ Flex: 0 1自动; } < div class = " title-hr”> < span > + < / span > <span class="hr fix"></span> 标题< span > < / span > < span class = "人力资源部" > < / span > < / div >

<div><span>text TEXT</span></div>

div { 
  height: 1px; 
  border-top: 1px solid black; 
  text-align: center; 
  position: relative; 
}
span { 
  position: relative; 
  top: -.7em; 
  background: white; 
  display: inline-block; 
}

为span设置padding,使文本和行之间有更多的空间。

例如:http://jsfiddle.net/tUGrf/

这里有一个解决方案,只需要2个属性,很容易更新使用CSS变量:

h2 { --s: 3px; /* the thickness */ --c: red; /* the color */ --w: 100px; /* the width */ --g: 10px; /* the gap */ border: 1px solid; border-image: linear-gradient( #0000 calc(50% - var(--s)/2), var(--c) 0 calc(50% + var(--s)/2), #0000 0) 0 1/0 var(--w)/0 calc(var(--w) + var(--g)); } h2 { font-size: 2rem; margin: 20px auto; width: fit-content; } body { font-family: system-ui, sans-serif; } <h2>I am a Title</h2> <h2 style="--g:50px;--c:purple">Adding some gap </h2> <h2 style="--w:100vw;--c:blue;--s:7px">Title</h2> <h2 style="--c:green;--s:5px;--w:50px;--g:20px">Another Title</h2>

我选择了一个更简单的方法:

HTML

<div class="box">
  <h1 class="text">OK THEN LETS GO</h1>
  <hr class="line" />
</div>

CSS

.box {
  align-items: center;
  background: #ff7777;
  display: flex;
  height: 100vh;
  justify-content: center;
}

.line {
  border: 5px solid white;
  display: block;
  width: 100vw;
}

.text {
  background: #ff7777;
  color: white;
  font-family: sans-serif;
  font-size: 2.5rem;
  padding: 25px 50px;
  position: absolute;
}

结果