我试着设计一个这样的标题:
html - 如何仅向主要元素而不是:before和:after添加背景色-LMLPHP
问题是,当我试图在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>

09-17 14:40
查看更多