我正在尝试为样式目的在文本字段中添加伪前后垂直线。 这些元素需要与文本对齐,距离左侧和右侧各-20像素。
当文本以inline-block的形式显示在一行时,这种做法效果很好,但是一旦文本跨越多行,它的宽度就会扩展到父级的宽度,并且伪元素不再离文本仅有20像素。
是否有一种方法可以使用CSS来实现这个目标?
当文本以inline-block的形式显示在一行时,这种做法效果很好,但是一旦文本跨越多行,它的宽度就会扩展到父级的宽度,并且伪元素不再离文本仅有20像素。
是否有一种方法可以使用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:before
和h2:after
上使用height: 100%;
吗? - fen1x<h2>
中使用空格来填充剩余的空间? - Jack Bashford