Aligning images within <div> tags

I have put an image within a div class and I cannot get it to centre like I did with the text, does anyone know how to code this? I have looked everywhere but I couldn’t find it.

Welcome to the commutiy, @ZoeySmailus! There are a couple of ways to do this (assuming your using HTML, JS, and CSS):

element {
  padding-left: (whatever centers it)px;
  padding-top: (whatever centers it)px;
}
element {
  margin-left: (whatever centers it)px;
  margin-top: (whatever centers it)px;
}

it’d be useful if you linked the repl. Aligning can involve different things depending on the page’s structure

Setting the margin and padding will only work on a specific screen size.
If you only want to center it horizontally, you can add text-align: center to the div.

If you want to center it vertically and horizontally, you can either use absolute positioning or make the div a flexbox:
1.

div {
  position: relative; /* This makes position: absolute be relative to this element */
}
img {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translateX(-50%)translateY(-50%); /* top: and left: set the top left corner of the element. This emulates setting the center */
}
div {
  display: flex;
  align-items: center;
  justify-content: center;
}

Like Umar said, the way you choose depends on your page structure

You can display the div element as a grid and center them using place-items:

.DIV_CLASS {
    display: grid;
    place-items: center;
}

This is the most effective way of centering items as it uses only two lines instead of the other methods that use three or more lines to position your images.

1 Like

Hi, @ZoeySmailus! Welcome to Replit Ask! Here are some solutions to your question:

Answer A: Use display: flex in CSS.

.div-class {
  display: flex;
  justify-content: center;
}

This works if you want only your image to be centered, and the image is the only element inside the <div> element.
If not, you can try making a new <div>, like so:

<div>
  <div class="div-class">
    <img src="https://something.com/assets/logo.png" />
  </div>

  <p>Lorem ipsum...
</div>

Answer B: Use text-align: center in the syntax above,
Answer C: Or use @Praquron’s answer.


Hope this helps! :slight_smile:
(P.S. if you need help with justify-content and align-items, see this).

1 Like