【问题标题】:css - shrink a parent div to fit one child's width and constrain the width of the other child [duplicate]css - 缩小父 div 以适应一个孩子的宽度并限制另一个孩子的宽度 [重复]
【发布时间】:2023-04-03 13:29:01
【问题描述】:

假设一个父 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。只需要现代浏览器解决方案

【问题讨论】:

    标签: css


    【解决方案1】:

    查看您的 jsFiddle 的 this edited version

    这是添加到 CSS 中的内容:

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

    【讨论】:

    • 太棒了。就行了!我应该知道该解决方案将包括表格显示,因为它是一个表格到 div 的翻译问题,我正在努力解决;)
    • 我亲眼目睹的这个巫术是什么!?
    【解决方案2】:

    @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>

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

      • 啊,我忘了提(我知道我会忘记一些事情)我正在寻找一个纯 CSS 的解决方案。
      • 对于这么简单的事情你真的不应该使用脚本。
      猜你喜欢
      • 2022-01-14
      • 2021-01-23
      • 1970-01-01
      • 2018-05-24
      • 2020-10-22
      • 2020-02-16
      • 2017-12-05
      • 1970-01-01
      • 2017-12-12
      相关资源
      最近更新 更多