将元素的宽度设置为兄弟的宽度

Set width of element to width of sibling

我有一个稍微不寻常的 CSS 挑战需要克服。

我有一个两栏布局,左栏的宽度由主图像的宽度设置,右栏可以填充剩余的 space。主图下方有一个容器,其自然宽度可以大于主图。但是,我希望这个 div 与主图像宽度相同,并且隐藏溢出。这是我尝试这样做的努力:

.outer {
  margin-right: 5px;
  position: relative;
}
.left {
  float: left;
}
.right {
  width: auto;
  overflow: hidden;
}
.contentOuter {
  overflow: hidden;
}
.content {
  width: 500px;
}
.inner {
  background-color: grey;
  color: white;
  width: 100%;
  height: 150px;
}
<div class="outer left">
  <div class="image">
    <img src="http://placehold.it/350x150" />
  </div>
  <div class="contentOuter">
    <div class="content">
      <img src="http://placehold.it/500x50" />
    </div>
  </div>
</div>
<div class="outer right">
  <div class="inner">
    Hello world!
  </div>
</div>

但如您所见,.contentOuter 会延伸到其内容的宽度,无论我尝试什么。

我要注意的一个主要问题是,除了 .content 具有固定宽度外,我不希望 CSS 中有任何其他硬编码宽度;一切都应该是完全流动的,列的尺寸由 .image img.

的尺寸决定

所以,我正在寻找 视觉上 看起来像这样的东西,但没有 .content 上的硬编码 max-width:

.outer {
  margin-right: 5px;
  position: relative;
}
.left {
  float: left;
}
.right {
  width: auto;
  overflow: hidden;
}
.contentOuter {
  overflow: hidden;
}
.content {
  max-width: 350px; /* Hard-coded for demo purposes */
}
.inner {
  background-color: grey;
  color: white;
  width: 100%;
  height: 150px;
}
<div class="outer left">
  <div class="image">
    <img src="http://placehold.it/350x150" />
  </div>
  <div class="contentOuter">
    <div class="content">
      <img src="http://placehold.it/500x50" />
    </div>
  </div>
</div>
<div class="outer right">
  <div class="inner">
    Hello world!
  </div>
</div>

一个选项,虽然这取决于您可能有的进一步要求,但它只需添加到下块:

position: absolute;
width: 100%;

这会将其从流中移除,并且封闭元素在调整大小时不会考虑其宽度,只会考虑顶部图像的宽度。 overflow: hidden 然后将隐藏溢出的内容。

缺点是封闭元素(或位置或后续元素)的高度不会考虑此元素的大小。

jsFiddle: https://jsfiddle.net/jacquesc/rsz0hb1g/

解决这个问题的一个快速方法是简单地使用一些 jQuery。只需两行代码即可实现。

var imgWidth = $('.image').width();
$('.content').width(imgWidth);