我试着做一个水平规则,中间有一些文本。 例如:
----------------------------------- 我的标题 -----------------------------
在CSS中有办法做到这一点吗?显然没有“-”号。
我试着做一个水平规则,中间有一些文本。 例如:
----------------------------------- 我的标题 -----------------------------
在CSS中有办法做到这一点吗?显然没有“-”号。
当前回答
编辑(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;此处使用)
其他回答
这大概就是我要做的:通过设置包含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/
如果有人想知道如何设置标题,使其显示在左侧的固定距离(而不是如上所示的居中),我通过修改@Puigcerber的代码来解决这个问题。
h1 {
white-space: nowrap;
overflow: hidden;
}
h1:before,
h1:after {
background-color: #000;
content: "";
display: inline-block;
height: 1px;
position: relative;
vertical-align: middle;
}
h1:before {
right: 0.3em;
width: 50px;
}
h1:after {
left: 0.3em;
width: 100%;
}
这里是JSFiddle。
使用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>
.hr-sect { 显示:flex; flex-basis: 100%; 对齐项目:中心; 颜色:rgba(0,0,0,0.35); Margin: 8px 0px; } .hr-sect::, {后.hr-sect:: 内容:“”; flex-grow: 1; 背景:rgba(0,0,0,0.35); 身高:1 px; 字体大小:0 px; 行高:0 px; Margin: 0px 8px; } < div class = " hr-sect " > < / div >文本
使用Bootstrap 4预定义类
<div class="row align-items-center">
<div class="col dropdown-divider"></div>
<div class="col-auto">OR</div>
<div class="col dropdown-divider"></div>
</div>