gpt4 book ai didi

html - 缩 child 子以适应 parent

转载 作者:行者123 更新时间:2023-11-28 02:41:42 26 4
gpt4 key购买 nike

我有一个具有可变数量子元素的固定大小的 div。我不知道 children 的大小。目标是缩小它们以适合父级。

例子:

.parent {
width: 100px;
height: 100px;
border: 2px dashed green;
}
.parent * {
max-width: 100%;
max-height: 100%;
}
<div class="parent">
<img src="https://placehold.it/250x400" />
<img src="https://placehold.it/300x250" />
</div>

max-width 等似乎单独将子级缩小到不大于父级;第一次爆出后的任何元素。

将它们全部包含在一起的想法?

最佳答案

CSS

在演示中,父级和图像完全相同,但有一个异常(exception):第一个父级为 200x200px,第二个父级为 100x100px。正如我们所见,子级完全符合父级的边界不管 parent 的尺寸如何。

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;
}
<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>

关于html - 缩 child 子以适应 parent ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43930231/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com