固定大小的边框底部

Sam*_*des 1 html css border

border在文本底部添加小号的最佳方法是什么?

必须border居中且最大20px,但文本可以很长,甚至200px.

所以就像:

<h1>This text can be longer than the border</h1>
<style>
.h1 {border-bottom:8px solid #000;}
</style>
Run Code Online (Sandbox Code Playgroud)

div我应该在 my 之后添加一个h1并为其设置最大尺寸吗?

dip*_*pas 7

您可以使用伪元素::after并使用left:50%/transform:translateX(-50%)在中间对齐,无论width

h1 {
  position: relative;
  display:inline-block;
  /* min-width:200px */
}
h1::after {
  border-bottom: 1px solid red;
  bottom: -10px;
  content: "";
  height: 1px;
  position: absolute;
  width: 20px;
  left:50%;
  transform: translateX(-50%);
}
Run Code Online (Sandbox Code Playgroud)
<h1>This text can be longer than the border</h1>
Run Code Online (Sandbox Code Playgroud)