我的 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>
我想像这样在这两个标题之间“画”一条线:
它应该适应标题的宽度:
(请原谅我的图像编辑技术)
是否有一种简单的纯 css 方法?
最佳答案
我认为最简单和最灵活的方法是使用Flexbox
。只需向 h1
和 h2
元素添加一些左右填充,这样行就可以总是比文本长一点。
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/