Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

html

css

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

like image 252
Boris Kozarac Avatar asked Dec 25 '22 06:12

Boris Kozarac


1 Answers

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>
like image 197
timolawl Avatar answered Mar 04 '23 19:03

timolawl