如何根据h标签的宽度设置p标签的宽度
How to set width of a p tag according to the width of a h tag
所以我有一个 <h>
标签和一个 <p>
标签。 <p>
标签的宽度需要跟随<h>
标签的宽度,<h>
标签的宽度会根据其文本的长度动态改变。
以下是示例
Example1:
Heading: this text will change from time to time
Paragraph: Width of this text needs to fit the
width of previous Heading tag. blah blah blah bl
ah blah blah lbah
Example2:
Heading: this text changed
Paragraph: Width of this
text also changed because
width of prevous heading
changed.
我无法使用 javascript,因此需要 css 或 html 解决方案。谢谢!
一种方法是 CSS table + table-caption。
.container {
display: table;
}
.container h2 {
margin: 0;
}
.container p {
display: table-caption;
caption-side: bottom;
background: #ccc;
padding: 5px;
}
<div class="container">
<h2>Short Heading</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas nec risus dignissim, varius nibh sed, dapibus tortor.</p>
</div>
<br/>
<div class="container">
<h2>Long Long Long Heading</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas nec risus dignissim, varius nibh sed, dapibus tortor.</p>
</div>
所以我有一个 <h>
标签和一个 <p>
标签。 <p>
标签的宽度需要跟随<h>
标签的宽度,<h>
标签的宽度会根据其文本的长度动态改变。
以下是示例
Example1:
Heading: this text will change from time to time
Paragraph: Width of this text needs to fit the
width of previous Heading tag. blah blah blah bl
ah blah blah lbah
Example2:
Heading: this text changed
Paragraph: Width of this
text also changed because
width of prevous heading
changed.
我无法使用 javascript,因此需要 css 或 html 解决方案。谢谢!
一种方法是 CSS table + table-caption。
.container {
display: table;
}
.container h2 {
margin: 0;
}
.container p {
display: table-caption;
caption-side: bottom;
background: #ccc;
padding: 5px;
}
<div class="container">
<h2>Short Heading</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas nec risus dignissim, varius nibh sed, dapibus tortor.</p>
</div>
<br/>
<div class="container">
<h2>Long Long Long Heading</h2>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas nec risus dignissim, varius nibh sed, dapibus tortor.</p>
</div>