<div id=“parent”>
<div id = "child1">
<img src="123"/>
</div>
<div id = "child2">
<p> Some text1 </p>
<p> Some text2 </p>
</div>
</div>
我有固定高度的父div。父div始终有2个子容器:
容器内的图像大小可能不同。有时,当图像较大时,它在#child1
和我的#child2
内会占用更多空间,并且文本仅变为半可见。我可以看到“ Some text1”段落,但看不到“ Some text2”。
如何使#child1
内的图像占据#parent
内的空间总是相同的百分比? (可能是通过放大)
答案 0 :(得分:0)
提供#child
和#child2
的宽度,然后将img
元素的宽度设为父元素的100%。
.parent {
height: 400px;
width: 500px;
}
.child {
width: 49%;
display: inline-block;
}
.child img {
width: 100%;
}
<div class=“parent”>
<div class="child">
<img src="https://thumbor.forbes.com/thumbor/1280x868/https%3A%2F%2Fspecials-images.forbesimg.com%2Fdam%2Fimageserve%2F42977075%2F960x0.jpg%3Ffit%3Dscale"/>
</div>
<div class="child">
<p> Some text1 </p>
<p> Some text2 </p>
</div>
</div>
答案 1 :(得分:0)
Flexbox对此非常棒。我已经在CSS中添加了注释,以解释每一行的作用。
* {
box-sizing: border-box;
/* border & padding are included in calculation of width */
}
.parent {
display: flex;
/* flexbox layout! */
background: papayawhip;
}
.child {
flex: 0 0 50%;
/* this is the layout of the child elements realtive to the flex container .parent, shorthand for flex-grow: 0; flex-shrink: 0; flex-basis: 50%; Think of flex-basis as the width you want the items to start at */
border: 1px solid dodgerblue;
padding: 20px;
/* some space around the edges inside */
}
#child1 {
display: flex;
/* give the child1 wrapper flexbox layout as well */
align-items: center;
/* vertical alignment */
justify-content: center;
/* horizontal alignment */
}
#child1 img {
max-width: 100%;
height: auto;
}
<div class="parent">
<div id="child1" class="child">
<img src="https://picsum.photos/200/300" />
</div>
<div id="child2" class="child">
<p> Some text1 </p>
<p> Some text2 </p>
</div>
</div>
答案 2 :(得分:0)
固定孩子的身高并使用背景图像会有所帮助。 overflow
将确保孩子的身高不超过 250px
#parent {
height:500px;
}
#child1, #child2 {
height: 250px;
overflow:auto;
width:100%;
}
#child1 {
background-size:contain;
background-position: center;
}
HTML
<div id="parent">
<div id="child1" style="background-image:url('path');"></div>
<div id="child2">Text</div>
</div>