简体   繁体   中英

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.

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.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM