css - 缩小父div以适合一个孩子的宽度并约束另一个孩子的宽度

时间:2012-10-05 13:14:03

标签: css

说,父div有两个子div,一个包含文本,另一个包含已知(但可变)宽度&的图像。高度。

我想

  • 第一个子(包含图像)div的宽度缩小以适合图像的宽度(我可以这样做)
  • 父div(未指定的宽度)缩小以适合包含图像的div的宽度(这也可以)
  • 包含文本的第二个子div(也是未指定的宽度)以匹配父div的宽度,而不管它包含的文本数量(这是它变得棘手的地方)。

我有一个可以完成我想要的工作版本直到第二个孩子的文本数量推动父div的宽度比图像的宽度更宽。

这是我的代码:

的CSS:

#container{border:1px solid #f00;display:inline-block;}
#child1{border:1px solid #0f0;}
#child2{border:1px solid #00f;}
img {border:1px solid #000;}

HTML:

<div id="container">
<div id="child1"><img src="//www.google.com/logos/2012/Teachers_Day_Alt-2012-hp.jpg" width="300" height="116"></div>
<div id="child2">Lorem ipsum dolor sit amet.</div>
</div>

这是一个jsfiddle: http://jsfiddle.net/BmbAS/1/

点击“延长/缩短文字”链接可以查看错误的位置,以增加文字数量

tldr - 我希望所有div的宽度都等于图像的宽度

PS。现代浏览器解决方案只需要

3 个答案:

答案 0 :(得分:24)

请参阅jsFiddle的this edited version

以下是CSS中添加的内容:

#container {
    display: table-cell;
}
#child1 {
    display: table-row;
    width: 1px;
}
#child2 {
    display: table-cell;
    width: 1px;
}

答案 1 :(得分:0)

@Chris提供的answer为我提供了以下很好的解决方案:我只需要将容器div适合第一个子元素(而剩下的子元素才能自动适应容器的宽度):

div.container {
    width: fit-content;
    max-width: 100%;
    margin: 16px auto;
    display: table;
}

div.inner-primary {
    display: block;
}

div.inner-rest {
    margin-top: 8px;
    display: table-caption;
    caption-side: bottom;
}
<div class="container">
  <div class="inner-primary"><div style="width:200px; border:1px dotted #ccc; border-radius:4px; padding: 4px;">This is the main element that drives the width of the container.</div></div>
  <div class="inner-rest">This is the first of the rest divs that fit automatically to the container...</div>
  <div class="inner-rest">This is the second element...</div>
</div>

答案 2 :(得分:-2)

如果您愿意使用一些小的javascript(本例中为jQuery),您可以使用图像div的宽度设置文本div的宽度。

尝试将$("#child2").css({'width': $('#child1').width()});添加到小提琴的JS末尾,或在此处查看分支:http://jsfiddle.net/VXEMu/

相关问题