html - 如何使其中一个垂直对齐的 child 缩小到其他 child 设置的宽度?

标签 html css

问题

有一个内联容器,其中有 2 个垂直堆叠的子容器。如下图:

Current layout

顶部的绿色子项应将其宽度缩小到底部橙色子项的宽度,将文本包裹在自身内部。所需的布局如下图所示:

Layout that I'd like to achieve

问题:单靠CSS怎么办?

其他情况

橙色容器比绿色容器宽(下图)。绿色保持其自然的最大宽度。请注意,即使解决方案会将绿框拉伸(stretch)到 100%,通过为绿框添加一个额外的容器然后将绿框置于其中居中,实现目标解决方案也很容易。

Orange container wider than the green one

橙色框比父级的最大可能宽度宽(下图)。橙色应该开始包装。

Orange box wider than the possible width of the parent

注意事项

  • 子项的内容是动态的 - 该解决方案需要处理宽度可变的子项。
  • 父级是内联的 - 它的宽度不是 100%,而是它最宽的子级的宽度。
  • 浏览器支持并不重要。解决方案甚至可以使用 CSS Grid。

代码

fiddle

http://jsfiddle.net/twfky2cr/24/

HTML

<div class="container">
  <div class="fitChild">
    Some long text that I would like to wrap to fit the container size
    set by the orange box
  </div>
  <div class="fullWidthChild">
    This one should set the container size
  </div>
</div>

CSS

.container {
  display: inline-flex;
  flex-direction: column;
  flex-wrap: nowrap;
  align-items: center;
  background-color: black;
}

.container,
.fitChild,
.fullWidthChild {
  padding: 10px;
}

.fitChild {
  color: white;
  background-color: green;;
}

.fullWidthChild {
  margin-top: 10px;
  background-color: orange;
}

最佳答案

我为您提供了部分解决方案。

http://jsfiddle.net/twfky2cr/166/

我正在为单元格使用 display: tablewidth:1px

<div class="table">
  <div class="row">
    <span class="cell wrap">
      Some long text that I would like to wrap to fit the container size
    </span>
  </div>
  <div class="row">
    <span class="cell nowrap">
      This one should set the container size
    </span>
  </div>
</div>

.table {
  background-color: Black;
  display: table;
  padding: 1rem;
}

.row {
  display: table-row;
}

.cell {
  padding: 1rem;
  display: table-cell;
  width: 1px;
}

.wrap {
  color: white;
  background-color: Green;
  white-space: wrap;
}

.nowrap {
  background-color: Orange;
  white-space: nowrap;
}    

关于html - 如何使其中一个垂直对齐的 child 缩小到其他 child 设置的宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51499219/

相关文章:

javascript - 随页面滚动绝对位置div

javascript - Jquery/Javascript 向 div 添加独特的类

CSS 对父级不透明,对子级不透明

html - 可见的彩色内容在 Chrome 中显示透明

javascript - 具有不同幻灯片时间的幻灯片放映

angularjs - 具有 Html5Mode 刷新页面问题的 Angular-UI-Router

Javascript 函数不适用于 html 中的多个按钮单击

html - 是否可以在 HTML 中为 Blade 模板编写 IF 内联

html - 在由 div 制成的类似表格的结构中,将列粘贴到左侧和顶部

html - 将按钮放入 Canvas 中