css - 收缩父div以适合一个孩子的宽度,并约束另一个孩子的宽度 [英] css - shrink a parent div to fit one child's width and constrain the width of the other child

查看:129
本文介绍了css - 收缩父div以适合一个孩子的宽度,并约束另一个孩子的宽度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

Say, a parent div has two child divs, one containing text, the other containing an image of known (but variable) width & height.

我想要


  • 第一个孩子的宽度包含div)缩小以适合图像的宽度(这是我可以做的)

  • 父div(未指定宽度)缩小以适合包含图像的div的宽度(这也是确定的)

  • 包含文本的第二个子div(也是未指定的宽度),以匹配父div的宽度,而不考虑它包含的文本数量难处理。)

我有一个工作版本,第二个孩子推动父div的宽度比图像的宽度宽。

I have a working version that does what I want until the quantity of text in the second child pushes the parent div's width wider than that of the image.

这是我的代码:

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/

and here's a jsfiddle: http://jsfiddle.net/BmbAS/1/

您可以通过点击lengthen /缩短文本链接以增加文本数量

you can see where it's going wrong by clicking the 'lengthen/shorten text' link to increase the quantity of text

tldr - 我希望所有的div都是相同的宽度,

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

ps. modern browser solution only necessary

推荐答案

请参阅

See this edited version of your jsFiddle.

以下是添加到CSS中的内容:

Here's what's added to the CSS:

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

这篇关于css - 收缩父div以适合一个孩子的宽度,并约束另一个孩子的宽度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆