我正在尝试在文本前后添加一行,但是我希望它能够响应,目前我唯一能找到的方法是使用width ...,因此它没有响应。
我宁愿只在psuedo元素之前和之后使用,但如果不可能,则可以使用另一种方法。
HTML:
<div class="section-header text-center">
<h2>Testing</h2>
</div>
CSS:
.section-header {
position: relative;
}
.section-header h2 {
border: 2px solid rgba(0, 0, 0, 0.1);
padding: 0.3em 0.8em;
display: inline-block;
}
.section-header::before,
.section-header::after {
border-top: 1px solid black;
display: block;
height: 1px;
content: " ";
width: 40%;
position: absolute;
left: 0;
top: 1.2em;
opacity: 0.1;
}
.section-header::after {
right: 0;
left: auto;
}
.text-center {
text-align: center !important;
}
答案 0 :(得分:2)
您可以考虑相对于h2
的伪元素,并依靠溢出来隐藏不需要的部分:
.section-header {
position: relative;
overflow:hidden; /*mandatory*/
}
.section-header h2 {
border: 2px solid black;
padding: 0.3em 0.8em;
display: inline-block;
position:relative;
}
.section-header h2::before,
.section-header h2::after {
content: " ";
width: 100vw; /*big value here*/
height: 1px;
position: absolute;
top: 0.6em;
background:black;
}
.section-header h2::after {
left: calc(100% + 40px); /*40px offset from the title*/
}
.section-header h2::before {
right: calc(100% + 40px);
}
.text-center {
text-align: center;
}
<div class="section-header text-center">
<h2>Testing</h2>
</div>
没有透明度的另一种想法是考虑如下的背景和阴影:
.section-header {
position: relative;
background:linear-gradient(black,black) center/100% 1px no-repeat;
}
.section-header h2 {
border: 2px solid black;
padding: 0.3em 0.8em;
display: inline-block;
position:relative;
background:#fff;
box-shadow:
40px 0 0 #fff,
-40px 0 0 #fff;
}
.text-center {
text-align: center;
}
<div class="section-header text-center">
<h2>Testing</h2>
</div>
答案 1 :(得分:1)
一个简单的选择是为section-header
使用 flexbox -然后您可以:
margin
的{{1}} h2
设置为100%-作为 flex项目,它将适应可用的空间 请参见下面的演示
width
.section-header {
position: relative;
display: flex; /* sets a flex container */
align-items: center; /* aligns vertically */
}
.section-header h2 {
border: 2px solid rgba(0, 0, 0, 0.1);
padding: 0.3em 0.8em;
display: inline-block;
margin: 0 1em; /* space between h2 and line if needed */
}
.section-header::before,
.section-header::after {
border-top: 1px solid black;
display: block;
height: 1px;
content: " ";
width: 100%; /* full-width ;)*/
top: 1.2em;
opacity: 0.1;
}
.text-center {
text-align: center !important;
}