I'm trying to style a heading to look like this:

The issue is that when I try to add a background color to the h2, it applies to the :before and :after content as well and spans the width of the page. I only want it applied to the h2.
I've tried adding a div inside the h2 and styling that instead of the 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>
I would do this differently without pseudo element:
.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>
You can also have each line alone if you want:
.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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With