我试着做一个水平规则,中间有一些文本。 例如:
----------------------------------- 我的标题 -----------------------------
在CSS中有办法做到这一点吗?显然没有“-”号。
我试着做一个水平规则,中间有一些文本。 例如:
----------------------------------- 我的标题 -----------------------------
在CSS中有办法做到这一点吗?显然没有“-”号。
当前回答
我选择了一个更简单的方法:
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;
}
结果
其他回答
编辑(09/2020)
显示:flex方法似乎是当今最可靠、最容易设置的方法。
写于3月17 '15 17:06:
对于后来(现在)的浏览器,display:flex和伪元素使得无需额外标记即可轻松绘制。
如果你需要花哨或难看的妆容,边框风格,盒影甚至背景也有助于化妆。 h1 {margin-top: 50 px; 显示:flex; 背景:线性渐变(向左、灰色、浅灰色,白色,黄色,绿色);; } H1:前,H1:后{ 颜色:白色; 内容:”; flex: 1; 边界底部:槽2 px; 保证金:汽车0.25 em; /* ou 0 1px si border-style:ridge */ } <h1>侧线通过flex</h1>
资源(2020年9月新增):
https://css-tricks.com/snippets/css/a-guide-to-flexbox/(参见这里使用的flex/flex-grow) https://css-tricks.com/the-peculiar-magic-of-flexbox-and-auto-margins/ (margin:auto 0.25em;此处使用)
我认为最直接的方法是使用CSS网格。
h1 { 显示:网格; Grid-template-columns: 1fr auto 1fr; 差距:1快速眼动; } h1::, {后h1:: 内容:“”; 顶部边缘:0.1雷姆重黑; align-self:中心; } <标题>标题< h2 >
这大概就是我要做的:通过设置包含h2的border-bottom来创建行,然后给h2一个较小的行高。然后将文本放在具有非透明背景的嵌套span中。
h2 { 宽度:100%; text-align:中心; Border-bottom: 1px实心#000; 行高:0.1 em; Margin: 10px 0 20px; } H2跨度{ 背景:# fff; 填充:0 10 px; } <h2><span>THIS IS A TEST</span></h2> <p>这是一些其他的内容</p>
我只在Chrome上进行了测试,但没有理由它不能在其他浏览器上运行。
JSFiddle: http://jsfiddle.net/7jGHS/
<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/
使用Bootstrap 4的人可以用这种方法实现。HTML代码中提到的类来自Bootstrap 4。
h1 {
position: relative;
flex-grow: 1;
margin: 0;
}
h1:before {
content: "";
display: block;
border-top: solid 2px blue;
width: 100%;
height: 1px;
position: absolute;
top: 50%;
z-index: 1;
}
h1 span {
background: #fff;
left: 12%;
padding: 0 15px;
position: relative;
z-index: 5;
}
然后像这样编写HTML
<div class="d-flex flex-row align-items-center">
<h1><span> Title </span> </h1>
</div>