Tribute Page Challenge - The <img> element should responsively resize, relative to the width of its parent element, without exceeding its original size. Would like to understand what's happening

Hey there, i’ve started freecodecamp lessons a couple of weeks ago, i’m going through Responsive Web Design Projects. Just finished the first one; everything worked fine except for the responsive image thing. I’ve already solved it after some google but i would like to understand the logics,

#image{
width:100%;
max-width:623px;
display: block; found this line in other post
margin: 0 auto; found this line in other post
}

Any guidance or explanation is appreciated, i would like to read further to understand this :smiley:

Welcome, juan.

Here is an extract from Mozilla Docs

<img> is a replaced element; it has a display value of inline by default, but its default dimensions are defined by the embedded image’s intrinsic values, like it were inline-block .

And here is an excellent description of why you might want inline or block.

As for the margin, the 0 is not needed, but the auto centers the image. (causes equal spacing on either side.

Hope this helps

1 Like

Hi, thanks for your answer :smiley:

I get the display:block will make the img occupy the whole line, while the margin:auto keeps it centered. Is that right?

It gets me confused that the page was already working as the example without those 2 lines(centered, size relative to parent, etc), but i guess it was just a coincidence.

Was the img in a container with display: flex by any chance?

Nope, only display line was the line added to the image after some google.

#main{
background-color: #e8e8e8;
border-radius:5px;
font-family: “Roboto”, Arial;
text-align:center;
color: #333;
font-size: 1.6rem;
line-height: 1.5;
padding:20px;
}

#img-div{
background-color: #ffffff ;
border-radius:5px;
padding: 10px;
margin: 0;
}

#image{
width:100%;
max-width:623px;
display: block;
margin: 0 auto;
}

There you can see the styles for my img parents, main->img-div->image.

PS: not sure if my posts has the right layout and stuff, i’m as new to the forum as i am to the web dev thing.

Juan, try taking off the text-align center . That might be what’s controlling the centered-ness of the img.

1 Like

Ok, i’ll after office time and see what happens! Thanks for your time!

Indeed, that was controlling the img align as other elements in the page. Would you say that was the incorrect way to do it? Site was working as excpected but not for the right reasons…

Seems to not be the recommended way:

This is also the way to center an image: make it into block of its own and apply the margin properties to it. For example:

IMG.displayed {
display: block;
margin-left: auto;
margin-right: auto }

https://www.w3.org/Style/Examples/007/center.en.html

1 Like