如何使垂直对齐的子项之一缩小到其他子项设置的宽度?

时间:2018-07-24 12:56:42

标签: html css

问题

有一个嵌入式容器,其中有2个垂直堆叠的子容器。下图:

Current layout

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

Layout that I'd like to achieve

问题:单独使用CSS怎么做?

其他情况

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

Orange container wider than the green one

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

Orange box wider than the possible width of the parent

注释

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

代码

提琴

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;
}

3 个答案:

答案 0 :(得分:1)

在此处http://jsfiddle.net/kjr9aghp/

查看此小提琴
$(document).ready(function() {

    $('.fitChild').width($('.fullWidthChild').width());

});

答案 1 :(得分:1)

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

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;
}    

答案 2 :(得分:-1)

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

 .container,
 .fitChild,
 .fullWidthChild {
   padding: 10px;
   width: 100% !important;
 }

 .mainwrapper{
   max-width:50%;
 }

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

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



<div class="container">
  <div class="mainwrapper">
    <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>
</div>