如何在h2之后放置具有固定宽度的居中边框底部?

Bor*_*rac 4 html css

如何border-bottomh2(根据文本可以更长或更短)之后以固定宽度(100px)居中放置?

代码

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;
}
Run Code Online (Sandbox Code Playgroud)
<h2>Something</h2>
Run Code Online (Sandbox Code Playgroud)

我正在尝试执行以下操作

在此处输入图片说明

小提琴

tim*_*awl 6

由于您有固定宽度的边框底部,您可以将其添加到h2:after {

margin-left: -50px;

想象一下left: 50%;将左边缘点移到中心。这意味着您的边框底部的最左端将位于中心点。这就是为什么你需要做margin-left: -50px;

这里有一些关于在 CSS 中居中的有用链接:

  1. w3c
  2. CSS 技巧

工作示例:

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;
}
Run Code Online (Sandbox Code Playgroud)
<h2>Something</h2>
Run Code Online (Sandbox Code Playgroud)