html - 如何仅将背景颜色添加到主要元素而不是:之前和:之后
问题描述
我正在尝试将标题设置为如下所示:
问题是当我尝试向 h2 添加背景颜色时,它也适用于 :before 和 :after 内容并且跨越页面的宽度。我只希望它应用于 h2。
我尝试在 h2 中添加一个 div 并对其进行样式设置而不是 h2。
.styled-heading {
text-align: center;
font-size: 32px;
background: black;
color: white;
}
.styled-heading:before {
content: " ";
display: inline-block;
margin: 0 0px 8px 0;
background-color: #999;
height: 3px;
width: 140px;
}
.styled-heading:after {
content: " ";
display: inline-block;
margin: 0 0 8px 00px;
background-color: #999;
height: 3px;
width: 140px;
}
<h2 class="styled-heading">Testing Testing</h2>
解决方案
如果没有伪元素,我会以不同的方式执行此操作:
.styled-heading {
font-size: 32px;
color: white;
display:table; /* to make the element fit the content */
margin:auto; /* to center */
/* The border will be the space for the lines*/
border-left:50px solid transparent;
border-right:50px solid transparent;
padding:5px 10px;
background:
/* main background cover only the padding*/
linear-gradient(green,green) padding-box,
/* the Line cover also the border area (width:100% height:3px)*/
linear-gradient(blue,blue) center/100% 3px border-box no-repeat;
}
<h2 class="styled-heading">Testing Testing</h2>
如果需要,您也可以单独使用每一行:
.styled-heading {
font-size: 32px;
color: white;
display:table; /* to make the element fit the content */
margin:auto; /* to center */
/* The border will be the space for the lines*/
border-left:50px solid transparent;
border-right:50px solid transparent;
padding:5px 10px;
background:
/* main background cover only the padding*/
linear-gradient(green,green) padding-box,
/* the Line cover also the border area*/
linear-gradient(blue,blue) left center/50% 3px border-box no-repeat,
linear-gradient(red,red) right center/50% 3px border-box no-repeat;
}
<h2 class="styled-heading">Testing Testing</h2>