使一个元素的宽度取决于其兄弟的宽度

时间:2016-11-10 19:02:44

标签: html css css3 flexbox

我试图制作一个小部件,使得副标题永远不会超过标题。因此标题将控制窗口小部件的宽度,如果字幕比标题宽,则字幕将会换行。如果可能的话,我会尝试不使用JavaScript。

我走近了(见下面的片段)。我能够将副标题人为缩短,但即使在这种情况下,由于某种原因,它所在的行也会扩展到适合容器的整个空间,而不仅仅是它的孩子使用的空间!事实上,它所占据的空间正如它没有被包裹的那样。



#container {
  background: #DDD; 
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.row {
  display: flex;
}

#subtitle {
  flex-basis: 0;
}

<div id="container">
  <div class="row">
    <h1 id="title">Title that is fairly long</h1>
  </div>
  <div class="row">
    <h3 id="subtitle">Subtitle that is a long subtitle and that is even longer and oh it is just so super!</h3>
  </div>        
</div>
&#13;
&#13;
&#13;

我需要在流程中保留字幕(不是position:absolute),并且标题需要能够包装,如果它变得超长(所以它不会只是溢出页面)。 有没有办法有两行,一个在另一个之下,而且一个只能和另一个一样长?

2 个答案:

答案 0 :(得分:3)

对我来说听起来像CSS表:

#container {
  background: #DDD; 
  display: table;
  width: 100%;
}
.row {
  display: table-row;
}
.row > * {
  display: table-cell;
}
.row:after {
  content: " ";
  display: table-cell;
}
#title {
  width: 1px;
  white-space: nowrap;
}
<div id="container">
  <div class="row">
    <h1 id="title">Title that is fairly long</h1>
  </div>
  <div class="row">
    <h3 id="subtitle">Subtitle that is a long subtitle and that is even longer and oh it is just so super!</h3>
  </div>        
</div>

标题上的

width:1px会导致该列崩溃。 white-space:nowrap阻止标题包装。由于它使用表格布局,这种组合会导致列的宽度由标题确定,因此字幕随之而来。 :after为我们提供了一个灵活的列来填写表格。

(一旦CSS Grid becomes available,这可能更合适。)

你提到了很长的头衔。有了这种可能性,您需要切换到Javascript。 (下面的Javascript需要在受影响的部分之后或者在页面加载时运行。)

var title = document.getElementById('title'),
    subtitle = document.getElementById('subtitle'),
    subtitleResize = function() {
      subtitle.style.width = title.clientWidth + 'px';
    };
window.addEventListener('resize', subtitleResize, false);
subtitleResize();
#container {
  background: #DDD; 
}

#title {
  display:inline-block;
}
<div id="container">
  <div class="row">
    <h1 id="title">Title that is fairly long</h1>
  </div>
  <div class="row">
    <h3 id="subtitle">Subtitle that is a long subtitle and that is even longer and oh it is just so super!</h3>
  </div>        
</div>

答案 1 :(得分:-1)

您已将white-space: nowrap;添加到h1标记,该标记为全宽

Please check the fiddle answer here

相关问题