htmlcssimagedivisionimage-resizing

how to use division-class for image in html css?


I am learning coding...newbie.

in html: case1 I created a class inside div

` <div class="image"> <img src="./.../imageabc.jpg" alt="abc photo"/> </div>`

in html: case2 I created a class inside img syntax

' <div> <img class="image" src="./.../imageabc.jpg" alt="abc photo"/> </div>`

in CSS : I set to resize the image or format image as needed:

` .image { width:100px; height:auto; }`

Outcome: case1 => did not work; while case2 it worked. I would like to ask if there is an explanation for the difference when placing a class inside image tag vs in a div which the image tag inside...as above example. thank you very much! PS: please ignore if there are the syntax error or typo...point here is the place i placed the class .


Solution

  • In the first case, you set the width of the 'image' div to 100px and it did in fact made the div 100px wide(if you use dev tools and inspect the div you can see the 'image' div is only 100px in width), but this doesn't mean that the child element(in this case the 'img') inherit the same width as parent. If you want the image to inherit its parent div's width,

    .image img {
     width:100%;
     height:auto;
    }
    

    Here we are making the 'img' inside of 'image' div have 100% width of its parent(which is 100px).