简体   繁体   English

当图像位于div中时,如何在HTML中将图像居中?

[英]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. 我在div内有一个图像,可以在图像上放置一个按钮。 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. 我试着使其成为自己的类,并将img标签本身居中,但它们似乎都不起作用。

 <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. 图片应居中于页面中间,因此我可以排成一行3。

In HTML: 在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: 要使图像居中,请将左右边距设置为auto并将其设置为block元素:

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

So, you can center any image while its inside a div. 因此,您可以将任何图像居中放置在div中。 I hope this might help you. 希望对您有所帮助。

You could position the .btn absolute to the relative container. 您可以将.btn绝对值.btn在相对容器中。 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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