cyliim
cyliim

Reputation: 301

How can I center an image in HTML while it's inside a div?

I have an image inside of a div to put a button on the image. I've searched around the web but can't find any way to center the image.

I've tried making it it's own class and centering the img tag itself, but none of them seem to work.

<div class="container">
  <img src="https://cdn.discordapp.com/avatars/543553627600584735/470015f633d8ae88462c3cf9fa7fd01f.png?size=256" alt="utili">
  <a href="utili.html" class="btn">Utili</a>
</div>

The image should be centered in the middle of the page, so I can line up 3.

Upvotes: 0

Views: 121

Answers (2)

Kashif Malik
Kashif Malik

Reputation: 109

In HTML:

<img src="paris.jpg" alt="Paris" class="center">

To center an image, set left and right margin to auto and make it into a block element:

.center {
  display: block;
  margin-left: auto;
  margin-right: auto;
  width: 50%;
}

So, you can center any image while its inside a div. I hope this might help you.

Upvotes: 2

davedeecoder
davedeecoder

Reputation: 235

You could position the .btn absolute to the relative container. If you know the size you want your image, even better.

How I would attempt to achieve it:

.container {
  position: relative;
  height: (the height of your image);
  width: (the width of your image);
}

img {
  position: relative;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.btn {
  position: absolute;
  bottom: (however far you want it from the bottom in pxs - so lets say 10px);
  left: 50%;
  transform: translateX(-50%);
  z-index: 2;
}

Upvotes: 1

Related Questions