it_is_a_literature it_is_a_literature - 6 months ago 9
HTML Question

How not to fill the whole body in browser?



div{
overflow:hidden;
border:1px solid red;
}
img{
width:160px;
height:160px;
padding:20px ;
}

<div>
<img src="http://i.imgur.com/MnmGmN7.jpg" />
</div>





The div will fill the whole body on my firefox.

It is not smart way ,when padding of img changed into 40px,the width of div will be changed into 160+40+40=240.

div{
width:200px;
border:1px solid red;
}


The desired effect is as below.

enter image description here

Answer

Use display: inline-block on the div and it will expand to its content instead of its parent width.

Side note, don't forget the required attribute alt="an image description"

div{
    display: inline-block;        /*  added  */
    overflow:hidden;
    border:1px solid red;
}   
img{
    width:160px;
    height:160px;
    padding:20px ;
} 
<div>
    <img src="http://i.imgur.com/MnmGmN7.jpg" alt="image description">
</div>

You can do this without the div as well, unless it is needed for a specific purpose.

img {
  width:160px;
  height:160px;
  padding:20px ;
  border:1px solid red;
}
<img src="http://i.imgur.com/MnmGmN7.jpg" alt="image description">

Comments