Boris Kozarac Boris Kozarac - 7 months ago 25
HTML Question

How to place centered border bottom with fixed width after h2?

How to place centered

border-bottom
with fixed width (100px) after
h2
(which can be longer or shorter depending on text)?

CODE



h2 {
position: relative;
z-index: 1;
text-align: center;
padding-bottom: 50px;
}
h2:after {
content: "";
position: absolute;
left: 50%;
bottom: 0;
width: 100px;
border-bottom: 2px solid magenta;
}

<h2>Something</h2>





I am trying to do following

enter image description here

Fiddle

Answer

Since you have a fixed width border bottom, you can add this to h2:after {:

margin-left: -50px;

Imagine left: 50%; shifting the left edge point to the center. This means that your border-bottom's left-most end would be at the center point. This is why you need to do margin-left: -50px;.

Here are some useful links on centering things in CSS:

  1. w3c
  2. CSS-Tricks

Working example:

h2 {
  position: relative;
  z-index: 1;
  text-align: center;
  padding-bottom: 50px;
}

h2:after {
  content: "";
  position: absolute;
  left: 50%;
  margin-left: -50px;
  bottom: 0;
  width: 100px;
  border-bottom: 2px solid magenta;
}
<h2>Something</h2>