Home > Software design >  How do I center an img within a div without the img shrinking?
How do I center an img within a div without the img shrinking?

Time:08-10

Centered Star in a div container

I used display: flex and justify-content: center to center the img within the div, it did in fact center the img but it shrank the img to a very small size. How do I center the img without having it shrink? I included a picture of this. I also tried re-sizing it with .img-star img { width: 3em; }, but it doesn't work. Pls help thanks.

.img-star {
  border: 1px solid white;
  padding: 20px;
  margin: 30px;
  border-radius: 50%;
  width: 45px;
  height: 45px;
  display: flex;
  justify-content: center;
}

CodePudding user response:

Not use flex. Use this CSS:

div {
  text-align: center;
}

CodePudding user response:

Don't use flex. just use this on your div

div {
  text-align: center
}

CodePudding user response:

Adding the align-items: center property could potentially fix it. It will also center the image vertically, if that is wanted.
I tried it with a div and it worked as intended It also appears to be fixing distorted images, such as this answer

img-star {
  border: 1px solid white;
  padding: 20px;
  margin: 30px;
  border-radius: 50%;
  width: 45px;
  height: 45px;
  display: flex;
  justify-content: center;
  align-items: center;
}

CodePudding user response:

set img display to block and set left right margins to auto, e.g.

.img-star {
    margin: 30px auto;
    display: block;
    padding: 20px;
    border: 1px solid white;
    border-radius: 50%;
    width: 45px;
    height: 45px;
}

You have also set the width of this class at 45px, so when this class is applied to an img it will be shrinking it to 45px. Try upping the width and height. width: 100%; height: 100%; will preserve your original image size to the max size of the block the image is in. Changing it based on px or em will set it to that e.g. width: 300px;.

  • Related