-1

When you give width to the line, the text-align: centre doesn't work how do I solve this?

.line-center {
  margin: 0;
  padding: 0 10px;
  background: #fff;
  display: inline-block;
}

h2 {
  text-align: center;
  position: relative;
  z-index: 2;
  width: 200px;
}

h2:after {
  content: "";
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  border-top: solid 1px red;
  z-index: -1;
}
<h2><span class="line-center">Test</span></h2>
David Thomas
  • 249,100
  • 51
  • 377
  • 410
Jskccc
  • 21
  • 5

1 Answers1

0

As you have given a width to the element you could use h2 { margin: 0 auto; } to set the left and right margins equal (within the containing element)

.line-center {
  margin: 0;
  padding: 0 10px;
  background: #fff;
  display: inline-block;
}

h2 {
  text-align: center;
  position: relative;
  z-index: 2;
  width: 200px;
  margin: 0 auto;
}

h2:after {
  content: "";
  position: absolute;
  top: 50%;
  left: 0;
  right: 0;
  border-top: solid 1px red;
  z-index: -1;
}
<h2><span class="line-center">Test</span></h2>
A Haworth
  • 30,908
  • 4
  • 11
  • 14