如何根据子内容大小扩展div?

时间:2015-03-14 22:40:23

标签: html css containers expand

我的观点有以下结构:

<div id="container_card">
    <div id="child_top_container">
        <div id="logo"><img src="http://placehold.it/175x100"></div>
        <div id="title"><p>This title block width depends on size of logo</div>
    </div>
    ...
</div>

Div #container_card具有固定的宽度和高度,即600px x 300px。此外,Div #child_top_container遵循相同的宽度,600px,但高度为125px。

儿童#logo的图像大小是随机的。我说随机,因为有时用户上传矩形和方形。

问题是,我想像这样显示块#title

+-------------------- 600px --------------------+
+-------------- #child_top_container -----------+
+                  +                            +
+ logo (175x100)   + This is title block        +
+                  +                            +
+------------------+----------------------------+
+------------ end #child_top_container ---------+
+-------------------- 600px --------------------+

如果图像的宽度小于上图,则如下所示:

+-------------------- 600px --------------------+
+-------------- #child_top_container -----------+
+                +                              +
+ logo (150x100) + This is title block          +
+                +                              +
+----------------+------------------------------+
+------------ end #child_top_container ---------+
+-------------------- 600px --------------------+

或类似的东西:

+-------------------- 600px --------------------+
+-------------- #child_top_container -----------+
+                     +                         +
+ logo (250x100)      + This is title block     +
+                     +                         +
+---------------------+-------------------------+
+------------ end #child_top_container ---------+
+-------------------- 600px --------------------+

我已经通过jQuery函数和使用window.resize事件实现了这一点,但是当我添加到carousel(bs3)时,有时看起来很难看。

问题是,我可以使用不依赖于js / jquery的纯css来实现一些解决方案吗?谢谢

因为不是我的母语而对我说糟糕的英语道歉。

1 个答案:

答案 0 :(得分:2)

显示:flex应该这样做:

.child_top_container {
  width:600px;
  border:solid;
  margin:auto;
  display:flex;
  align-items:center;
}
#title {
  flex:1;
  text-align:center;
}
img {
  display:block;
}
<div class="child_top_container">
  <div id="logo"><img src="http://placehold.it/175x100"></div>
  <div id="title"><p>This title block width depends on size of logo</div>
</div>
<div class="child_top_container">
  <div id="logo"><img src="http://placehold.it/150x100"></div>
  <div id="title"><p>This title block width depends on size of logo</div>
</div>
<div class="child_top_container">
  <div id="logo"><img src="http://placehold.it/300x120"></div>
  <div id="title"><p>This title block width depends on size of logo</div>
</div>

看看https://css-tricks.com/snippets/css/a-guide-to-flexbox/