比方说,父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;}
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
这里有一个jsfiddle:http: //jsfiddle.net/BmbAS/1/
您可以通过单击"延长/缩短文本"链接来查看出错的位置,以增加文本数量
tldr - 我希望所有的div都是相同的宽度,它等于图像的宽度
PS.现代浏览器解决方案只需要
Chr*_*ris 24
查看jsFiddle的此编辑版本.
这是CSS中添加的内容:
#container {
display: table-cell;
}
#child1 {
display: table-row;
width: 1px;
}
#child2 {
display: table-cell;
width: 1px;
}
Run Code Online (Sandbox Code Playgroud)
@Chris 提供的答案引导我找到以下针对我的情况的绝佳解决方案,其中我需要将容器 div 仅适合第一个子元素(并让其余子元素自动适合容器的宽度):
.wrapper { /* optional container */
width: fit-content; /* essential prop */
max-width: 100%;
margin: 16px auto;
background-color: #efefef;
padding: 1rem;
border-radius: 0.5rem;
}
.container {
width: fit-content; /* essential prop */
display: table; /* essential prop */
}
.inner-primary {
display: block; /* essential prop */
background-color: white;
padding: 0.8rem;
border-radius: 0.3rem;
}
.inner-rest {
display: table-caption; /* essential prop */
caption-side: bottom; /* essential prop */
margin-top: 1rem;
padding: 0 0.2rem;
}Run Code Online (Sandbox Code Playgroud)
<div class="wrapper">
<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>
</div>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
12684 次 |
| 最近记录: |