我有一个固定大小的 div,其子元素的数量可变。我事先不知道孩子们的尺寸。目标是缩小它们以适应父级。
例子:
.parent {
width: 100px;
height: 100px;
border: 2px dashed green;
}
.parent * {
max-width: 100%;
max-height: 100%;
}Run Code Online (Sandbox Code Playgroud)
<div class="parent">
<img src="https://placehold.it/250x400" />
<img src="https://placehold.it/300x250" />
</div>Run Code Online (Sandbox Code Playgroud)
max-width等似乎单独将孩子缩小到不大于父母;第一个爆发之后的任何元素。
有想法将它们全部包含在一起吗?
display使用table值使节点符合其父级的尺寸。position为relative父母和absolute孩子,以便将他们保持在父母的边界内。在演示中,父级和图像相同,但有一个例外:第一个父级为 200x200px,第二个父级为 100x100px。正如我们所看到的,无论父级的尺寸如何,子级都完美地符合父级的边界。
详情见demo中评论
.parent {
width: 200px;
height: 200px;
border: 2px dashed green;
/* Behaves like a table
|| which means that any
|| table elements and elements
|| styled to behave like a
|| table element will conform
|| to it's parent while maintaining
|| it's aspect ratio.
*/
display: table;
/* This will enable children to stay
|| within it's borders if they are
|| absolutely positioned
*/
position: relative;
}
.ver2 {
width: 100px;
height: 100px;
}
.parent * {
max-width: 100%;
max-height: 100%;
/* Behaves as a <td> which means
|| it will naturally shrink to
|| conform to the dimensions
|| of it's parent if it is a
|| table or an element styled
|| to behave like a table and
|| keep it's aspect ratio.
*/
display: table-cell;
/* It will stay within the confines
|| of the borders of it's parent
|| (unless it's given negative
|| values)
*/
position: absolute;
}
img:first-of-type {
top: 0;
left: 0;
/* Layered on top of img1
|| to show it's position
|| within the parent
*/
z-index: 1;
/* used to show where img1 is. */
opacity: .5;
}
img:last-of-type {
bottom: 0;
right: 0;
}
.demoOnly {
float: right;
display: inline-block;
}Run Code Online (Sandbox Code Playgroud)
<div class='demoOnly'>
<div class="parent ver2">
<img src="https://placehold.it/250x400/f00/fcf?text=img1" />
<img src="https://placehold.it/300x250/fc0/f00?text=img2" />
</div>
<span>Parent is 100x100px<br>
img1 is AR 5:8 - 62.5x100px<br>
img2 is AR 6:5 - 100x83px</span>
</div>
<div class="parent">
<img src="https://placehold.it/250x400/f00/fcf?text=img1" />
<img src="https://placehold.it/300x250/fc0/f00?text=img2" />
</div>
<span>Parent is 200x200px<br>
img1 is AR 5:8 - 125x200px<br>
img2 is AR 6:5 - 200x166px</span>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8020 次 |
| 最近记录: |