Reputation: 426
<div id=“parent”>
<div id = "child1">
<img src="123"/>
</div>
<div id = "child2">
<p> Some text1 </p>
<p> Some text2 </p>
</div>
</div>
I have parent div with fixed height. Parent div always have 2 child containers:
The image inside the container can be different in size. Sometimes, when image is larger, it takes more space inside #child1
and my #child2
with text becoming only half-visible. I can see the "Some text1 " paragraph, but not "Some text2".
How can I make my image inside #child1
take always same % of space inside #parent
? (Probably, by zooming it in)
Upvotes: 0
Views: 155
Reputation: 1825
Fixing height of the children and using background image will help. overflow
will make sure that the height of the child does not go beyond 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>
Upvotes: 0
Reputation: 2996
Flexbox is awesome for this. I have included comments in the CSS that explain what each line does.
* {
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>
Upvotes: 1
Reputation: 1666
Give #child
and #child2
width, then make the img
element's width 100% of the parent.
.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>
Upvotes: 1