如何根据h标签

时间:2016-01-19 00:16:10

标签: html css width

所以我有一个<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解决方案。谢谢!

1 个答案:

答案 0 :(得分:4)

使用CSS table + table-caption可以做到这一点。

<强> Oniguruma

&#13;
&#13;
.container {
  display: table;
}
.container h2 {
  margin: 0;
}
.container p {
  display: table-caption;
  caption-side: bottom;
  background: #ccc;
  padding: 5px;
}
&#13;
<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>
&#13;
&#13;
&#13;