html - 有没有办法拉伸(stretch)父 div?

标签 html css

我的问题不是很具体,所以我可以在没有示例的情况下提出问题,所以这是我的情况:假设我有一个图书列表,我在父 div 中显示它,它具有维度。列表可能大于或不大于父 div,但如果是这样,则有滚动条。这本书有它的标题和一些带有服务器端定义宽度的可选规范。

我需要的是,书籍规范会拉伸(stretch)内部容器,但标题不会,被省略号截断。

我只能用一些js来做,感觉很蹩脚,所以请问有没有办法只用css来做?

<div id="outer">
  <div id="inner">
    <div class="book">
      <div class="title">The Persecution and Assassination of Jean-Paul Marat as Performed by the Inmates of the Asylum of Charenton Under the Direction of the Marquis de Sade</div>
      <div class="attrs">
        <div class="item" style="width:200px">Author: Peter Weiss</div>
        <div class="item" style="width:200px">Rating: 4.03</div>
        <div class="item" style="width:300px">Published December 1st 2001 by Waveland Pr Inc (first published 1963)</div>
      </div>
    </div>
    <div class="book">
      <div class="title">1984</div>
      <div class="attrs">
        <div class="item" style="width:200px">Author: George Orwell</div>
        <div class="item" style="width:200px">Rating: 4.15</div>
      </div>
    </div>
  </div>
</div>

这是用来说明的笔:https://codepen.io/Masquer/pen/rdwJzQ

最佳答案

实际问题比您的代码所指示的要简单得多,但如下所示:
#inner 容器的宽度应由其内容决定(不包括标题),标题仅与容器一样宽。不管内容的宽度。就是这样。

所以解决方案很简单:不要让标题影响宽度。换句话说,给标题 position: absolute

#inner {
  background:#bbb;
  display:inline-block;
}

.title {
  background:#ddd;
  height:30px; margin:1em;
  position:relative;
}

.title > span {
  position:absolute;
  width:100%; line-height:30px;
  white-space:nowrap;
  overflow:hidden;
  text-overflow:ellipsis;
}
.contents {
  background:#ddd;
  margin:1em;
}
.contents img {
  vertical-align:top;
}
<div id="inner">
 <div class="title">
  <span>A very, very, very, very, very, very, very, very, very, very, very, very, very, very long title</span>
 </div>
 <div class="contents">
  <img src="https://placehold.it/400x100" alt="400x100">
 </div>
</div>

在这个例子中,我从来没有在任何地方设置像素宽度,所以它和里面的图片一样宽,忽略标题的宽度。 (您可以使用不同的图片或文字,它会调整到新的宽度。)

我花了一段时间才想出解决方案,但您示例的结构起初将我推向了错误的方向。对不起。例如,#outer 容器不是演示问题所必需的。如果需要,您可以在此代码周围放置一个外部容器。

关于html - 有没有办法拉伸(stretch)父 div?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49462294/

相关文章:

html - 名称属性中的方括号有什么用?

html - 在 safari 中使用 1px 分隔线(选项)选择框

Html,Css 问题与 ul 和 Ll

css - 使用 Angular 7 cli 解析 css 中的 Assets 路径

javascript - 如何激活模式以在所有 3 个按钮上单击而不是只用一个按钮打开?

java - Android将HTML文件从本地文件夹加载到WebView中

html - 正确对齐表格

html - 我的 Django 模板中的问题居中页脚

html - 如何水平居中带有 anchor 链接的div?

html - Bootstrap 4 导航侧不平滑/生涩/毛刺