让容器宽度与其第一个元素一样宽,其他元素保持最大尺寸

Have the container width be as wide as it's first element, and other elements keep that maximum size

<div class="content">
    <h2>This is a long heading</h2>
    <p>This is a long text but it should be the same width as the h2, not wider nor narrower Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur temporibus commodi expedita debitis nisi accusantium, saepe dolorem sapiente eum suscipit quod vitae!</p>
</div>

Css

.content {
    background-color: tomato;
    color: #fafafa;
    padding: 10px;
    margin: 40px;
}

基本上我的代码是第一个例子,我希望它和第二个例子一样。 与H2宽度相同的容器(后端生成)。

如果 h2 有 2 个单词,那么它下面的段落应该匹配宽度,如果 h2 有 20 个单词,则应该发生同样的情况(使用极端作为指导)。

Better check fiddle here

寻找 css 唯一的解决方案

有一种方法,但它不适用于一般布局..但是,FWIW。

根据偏好,我会使用更灵活的布局方法或 javascript。我怀疑这个选项不是 robust.

.content {
  display: table;
  border: 1px solid grey;
  /* note does not extend to paragraph */
}
.content h2 {
  display: inline-block;
}
.content p {
  display: table-caption;
  caption-side: bottom;
  text-align: justify;
}
<div class="content">
  <h2>This is a long heading</h2>

  <p>This is a long text but it should be the same width as the h2, not wider nor narrower Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur temporibus commodi expedita debitis nisi accusantium, saepe dolorem sapiente eum suscipit quod
    vitae!</p>

  <p>This is a long text but it should be the same width as the h2, not wider nor narrower Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur temporibus commodi expedita debitis nisi accusantium, saepe dolorem sapiente eum suscipit quod
    vitae!</p>
</div>

JSfiddle Demo

确保强大的向后兼容性的唯一方法是 Javascript。 我会避免 "table" 显示;我不记得所有的支持情况,但它在某种程度上是有问题的。 我要补充一点,我没有发现使用 Divs 只是为了再次在表格中转换它们的好编码...

总而言之,只有两行代码:

function setWidth(id) {
 w=$("#header").css("width");
  $(id).css( "width", w);
}
setWidth(inner)

css 部分:

.content {
   background-color: tomato;
   color: #fafafa;
   padding: 10px;
   margin: 40px;
   display:inline-block

 }
 h2 {
    display:inline
  }

HTML:

<div class="content">
   <h2 id="header">This is a long text</h2>
   <p id="inner">This is a text that expands accordling with H2 header other text, other and other...</p>
</div>

Working Feedle here