我有一个固定大小的div,其中包含可变数量的子元素。我不提前知道孩子的大小。目标是缩小它们以适合父母。
示例:
.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
等似乎单独将一个孩子缩小为不大于父母;第一次爆发后的任何元素。
想要将它们全部包含在一起?
答案 0 :(得分:2)
display
with table
values使节点符合其父级的维度。position
with relative
for parent and absolute
for children,以便将它们保留在父母的边界内。在演示中,父母和图像都是相同的但有一个例外:第一个父亲是200x200px,第二个父亲是100x100px。我们可以看到,孩子们在父母的边界内完全符合无论父母的维度如何。
详情在演示
中发表
.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>
答案 1 :(得分:-1)
您可以在css属性中使用position: absolute
尝试此操作。无论何时缩小它,孩子都适合父母。如果您有任何问题,请在下面评论。快乐的编码! :)
.parent{
padding: 10px;
border: solid 1px #363636;
width: 90%;
height: 300px;
}
.child{
position: absolute;
border: solid 1px red;
width: 80%;
height: 200px;
text-align: center;
padding: 10px;
}
<div class="parent">
<div class="child">
Child
</div>
</div>