【问题标题】:How to set width of a p tag according to the width of a h tag如何根据h标签的宽度设置p标签的宽度
【发布时间】:2016-04-24 07:36:04
【问题描述】:

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

【问题讨论】:

  • 请查看此链接:source
  • 如果您包含现有的 html 和 css,我认为它可以更准确地帮助您。所以他们的答案将使用你的例子而不是他们的例子。
  • @Michael 谢谢哥们,但我的问题解决了另一个问题。
  • @bot 你是对的,下次应该这样做。谢谢!

标签: html css width


【解决方案1】:

一种使用 CSS 表格 + 表格标题的方法。

jsfiddle

.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>

【讨论】:

  • 很好,display: table-caption; 做了什么其他人不做的?
  • @LGSon 它通常用于使图像标题宽度与图像宽度相匹配。标题元素(或 css 表格标题)参与表格模型。您可以从spec 了解更多信息。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-02-18
  • 1970-01-01
  • 2014-12-18
  • 1970-01-01
相关资源
最近更新 更多