blueSky
blueSky

Reputation: 247

How to keep a div inline-block with an image inside?

.parent{
background:silver;
text-align:center;
display:inline-block;
}

.child{
background:gold;
display:inline-block;
}

.imginside{
display:inline-block;
width:50%;
}
<div class='parent'>
<div class='child'>

<img class='imginside' src='https://static.businessinsider.com/image/50db38a069bedd0d1000000c-750.jpg' alt='img'>

</div>

</div>

If a text is inside child - it is inline-block.

But if an image is inside child - child becomes block (background gold is 100% wide);

How to keep child - inline-block with an image inside?

Upvotes: 2

Views: 5305

Answers (2)

Temani Afif
Temani Afif

Reputation: 272965

Simply add width:50% to the div and make the image max-width:100%;

.parent {
  background: silver;
  text-align: center;
  display: inline-block;
}

.child {
  background: gold;
  display: inline-block;
  width: 50%;
}

.imginside {
  display: inline-block;
  vertical-align:top;
  max-width: 100%;
}
<div class='parent'>
  <div class='child'>

    <img class='imginside' src='https://static.businessinsider.com/image/50db38a069bedd0d1000000c-750.jpg' alt='img'>

  </div>

</div>

Upvotes: 2

Arex
Arex

Reputation: 694

Firstly, with the image inside the child remains inline-block. To check, inspect the child element (use devtools on chrome). In the element style it will show display:inline-block. What the problem is that you have given width:50% to the image. Try using more absolute units like px. I have provided a working example:

.parent{
background:silver;
text-align:center;
display:inline-block;
}

.child{
background:gold;
display:inline-block;
}

.imginside{
display:inline-block;
padding:10px;
}
<div class='parent'>
<div class='child'>

<img class='imginside' src='https://static.businessinsider.com/image/50db38a069bedd0d1000000c-750.jpg' alt='img'>

</div>

</div>

It was working for text as you had not given %width to it. Hope this clears things out.

Upvotes: 3

Related Questions