html - 如何在两个标题之间绘制理想线?

标签 html css markup

我的 HTML 代码有这样的结构:

h1 {
  text-align: center;
  font-size: 20pt;
  padding-bottom: 0;
}

h2 {
  text-align: center;
  font-size: 16pt;
}

<body>
  ...
  <div id="container">
    <h1>Title</h1>
    <h2>Sub</h2>
  </div>
  ...
</body>

我想像这样在这两个标题之间“画”一条线:

title - sub

它应该适应标题的宽度:

longer title - sub

title - longer subtitle

(请原谅我的图像编辑技术)

是否有一种简单的纯 css 方法?

最佳答案

我认为最简单和最灵活的方法是使用Flexbox。只需向 h1h2 元素添加一些左右填充,这样行就可以总是比文本长一点。

body {
  text-align: center;
}
.container {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
}
h1 {
  font-size: 20px;
  padding: 0 10px;
}
h2 {
  font-size: 16px;
  padding: 0 10px;
}
.line {
  height: 3px;
  width: 100%;
  background: red;
}
<div class="container">
  <h1>Lorem ispum</h1>
  <span class="line"></span>
  <h2>Sub</h2>
</div>
<hr>
<div class="container">
  <h1>Ispum</h1>
  <span class="line"></span>
  <h2>Lorem ipsum dolor sit amet.</h2>
</div>

更新:您实际上可以使用 .container 上的伪元素执行此操作,但您需要指定顺序,以便该行显示在 h1 元素之后。

body {
  text-align: center;
}
.container {
  display: inline-flex;
  flex-direction: column;
  align-items: center;
}
.container > h1 {
  order: 1;
  font-size: 20px;
  padding: 0 10px;
}
.container > h2 {
  padding: 0 10px;
  order: 3;
}
.container:before {
  content: '';
  height: 3px;
  width: 100%;
  background: red;
  order: 2;
}
<div class="container">
  <h1>Lorem ispum</h1>
  <h2>Sub</h2>
</div>
<hr>
<div class="container">
  <h1>Ispum</h1>
  <h2>Lorem ipsum dolor sit amet.</h2>
</div>

关于html - 如何在两个标题之间绘制理想线?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40959661/

相关文章:

jquery - 多个全屏 div 相互叠加

javascript - 保存字体文件以供离线查看

html - 有效的 HTML 和 TD 元素的数量

html - 如何使用如下所示的 htaccess 文件创建无扩展名 url?

javascript - insideHTML 替换整个文档

html - webkit 自动填充输入的光标颜色

css - IE 7 是否支持内容伪类?

css - 如何覆盖 chrome 中的嵌入样式?

javascript - 无法编辑 Flickity-view(Flickity 插件)

jquery - 制作像 jgrowl 一样的 float div