如何使HR元素与其上方文本的宽度相同

Joh*_*n R 2 html css twitter-bootstrap

我希望这个特定HR的宽度与任何屏幕尺寸上方的"LARGER HEADER LIKE"相同.我有一个小于245px的默认宽度,但对于这个特定的宽度,我希望与任何屏幕尺寸的上面文本的宽度相同

hr {
  border-top: 0px solid blue !important;
  padding: 0;
  margin-top: 0.5em !important;
  border-width: 6px !important;
  width: 245px;
}
Run Code Online (Sandbox Code Playgroud)
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet"/>
    <div class="container">
       <div class="row text-center">
          <h1>HEADER 1</h1>
       </div>
       <div class="row text-center">
          <h1>LARGER HEADER LIKE THIS</h1>
          <hr>
       </div>
Run Code Online (Sandbox Code Playgroud)

Mic*_*ker 5

更好的方法是将hr样式用作要应用它的文本的伪元素.这是一个例子.

.hr {
  display: inline-block;
}
.hr:after {
  content: '';
  display: block;
  border-top: 6px solid blue;
  margin-top: 0.5em;
}
Run Code Online (Sandbox Code Playgroud)
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
  <div class="row text-center">
    <h1>HEADER 1</h1>
  </div>
  <div class="row text-center">
    <h1 class="hr">LARGER HEADER LIKE THIS</h1>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)

但你也可以嵌套hrh1和限制大小h1的宽度利用的内容匹配display: inline-block; float: left/right;position: absolute

h1 {
  display: inline-block;
}
hr {
  border-top: 0px solid blue !important;
  padding: 0;
  margin-top: 0.5em !important;
  border-width: 6px !important;
}
Run Code Online (Sandbox Code Playgroud)
<link href="//netdna.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" rel="stylesheet" />
<div class="container">
  <div class="row text-center">
    <h1>HEADER 1</h1>
  </div>
  <div class="row text-center">
    <h1>
      LARGER HEADER LIKE THIS
      <hr>
    </h1>
  </div>
</div>
Run Code Online (Sandbox Code Playgroud)