我正在尝试在垂直线之前和之后向文本字段添加伪造的样式目的。这些元素需要与文本齐平 -20px 左侧和 -20px 右侧。
当文本作为行内 block 在一行上时,这工作正常,但一旦文本跨越多行,宽度就会扩展到父元素的宽度,并且伪元素不再距离文本只有 20px。
有没有一种方法可以使用 CSS 完成此操作?
.container {
width: 500px;
background-color: red;
text-align: center;
margin-left: 40px;
}
h2 {
position: relative;
display: inline-block;
margin: 0;
padding: 0;
background-color: blue;
color: white;
}
span {
position: relative;
background-color: green;
}
h2::before,
h2::after {
content: '';
position: absolute;
top: 0;
width: 4px;
height: 20px;
background: black;
}
h2::before {
left: -20px;
}
h2::after {
right: -20px;
}
<!-- Single line example works as the black bars are 20px away from the start/end of text-->
<div class="container">
<h2><span>This is a title</span></h2>
</div>
<br> <br>
<!-- double line doesn't work because the h2 is now the full width of the container -->
<div class="container">
<h2><span>This is loooonnggggggggggggggggggggggeeeeerrr</span></h2>
</div>
编辑:这是一个使用表格的工作版本,但如果有人有更好的解决方案,我很想听听:https://codepen.io/anon/pen/MqveLQ
最佳答案
因此,据我所知,这里的问题是您在何处应用前后边框。您需要更改应用边框的位置。从 h2 中删除它们,并添加一个新的 html 元素来包装 h2 并在那里应用。
例如:
<div class="container">
<div class="headerwrap">
<h2><span>This is loooonnggggggggggggggggggggggeeeeerrr</span></h2>
</div>
</div>
<div class="container">
<div class="headerwrap">
<h2><span>This is a title</span></h2>
</div>
</div>
CSS
.headerwrap::before,
.headerwrap::after {
content: '';
position: absolute;
top: 0px;
bottom:0;
margin:auto;
width: 4px;
height: 20px;
background: black;
}
.headerwrap::before {
left: 10px;
}
.headerwrap::after {
right: 10px;
}
这是一个工作示例:https://codepen.io/FEARtheMoose/pen/VGbJjO?editors=1100#0
编辑:评论后更改示例 - https://codepen.io/FEARtheMoose/pen/VGbJjO
关于html - 将伪类 "before"和 "after"应用于多行文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52161414/