Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add background color only to main element and not :before and :after

Tags:

html

css

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

enter image description here

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>
like image 908
cjk47 Avatar asked Oct 29 '25 13:10

cjk47


1 Answers

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>
like image 142
Temani Afif Avatar answered Nov 01 '25 01:11

Temani Afif