我的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>
Run Code Online (Sandbox Code Playgroud)
我想在这两个标题之间"画"一条线,如下所示:
它应该调整到标题的宽度:
(请原谅我的图像编辑技巧)
有一种简单的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;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
更新:您实际上可以使用伪元素执行此操作,.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;
}Run Code Online (Sandbox Code Playgroud)
<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>Run Code Online (Sandbox Code Playgroud)
您可以用一个简单的pseudo元素来处理这个问题。不改变html结构,不支持跨浏览器的css。我们需要在父级上使用display 并在 上table创建一个新元素(带有 的边框) 。pseudo<h1>
看这个例子:
#container {
display: table;
margin: 0 auto;
text-align: center;
}
h1:after {
content:"";
position: absolute;
bottom: 0;
left: 0;
width: 100%;
border-bottom: 3px solid red;
}
h1, h2 {
margin: 5px 0;
padding: 0 10px 5px;
}
h1 {
position: relative;
font-size: 20pt;
}
h2 {
font-size: 16pt;
}Run Code Online (Sandbox Code Playgroud)
<div id="container">
<h1>long long title</h1>
<h2>Sub</h2>
</div>
<div id="container">
<h1>h1</h1>
<h2>Sub</h2>
</div>
<div id="container">
<h1>h1</h1>
<h2>long long subtitle</h2>
</div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
406 次 |
| 最近记录: |