Centering images

Centering images
0

#1

Here, is my current progress on project 1, designing a tribute page.

The CSS below seems to center my images nicely when I’m at a medium to large screen but when I reduce the size the images hug the left side of their respectives divs. Can anyone explain why this is? (Considering this happens around the screen size where I change the max-width property of my images I’m guessing this collides with other CSS in some way.)

#img-div {
  margin: 0 auto;
}

#2

Add a text-align-center, and see if that helps. Fyi: the project looks good so far.


#3

Thank you on both accounts. Adding text-align: center on the div solves the issue. :smiley:


#4

Change your #img-div to be displayed as block


#5

This doesn’t seem to work, if you reduce my project to less than 820px (where the image currently takes up its own line) it’ll be off center without text-align: center. I think me reducing the pictures max-width is the cause of the issue?


#6

Sorry, I meant #img-div img, not #img-div.

You can also move your margin: 0 auto from the div to the image itself and remove any styling (and id since it will no longer be required) from the parent div. You don’t want to have set this margin on your parent div because it eats some of the available space for the image’s width, making it smaller sooner than necessary.

So your code would like this:

#img-div no longer exists

(change this from #img-div img)
img {
  border-radius: 32px;
  max-width: 100%;
  display: block;
  margin: 0 auto;
}

You can also use the previous solution and use text-align: center but in that case I recommend that you still remove margin: 0 auto from the parent div so that image will stay more responsive.

Both solutions do the job :slight_smile:

Also, you don’t want to use the same id on multiple elements in your HTML, if it’s a repeated element, use class instead. And you don’t need to give your images an id of “img”, they can already be targeted in CSS simply with “img { ... }” , which by the way you have been doing anyway :stuck_out_tongue: If you want to target a specific image then giving them an id/class is a good option, but in this case you’re styling both images the same way.


#7

Oops not sure how I didn’t notice having multiple ids! Thank you the tips, they’re very helpful.