【问题标题】:How can I center an image in HTML while it's inside a div?如何在 div 中将图像居中放在 HTML 中?
【发布时间】:2019-03-30 03:13:06
【问题描述】:

我在 div 中有一个图像,可以在图像上放置一个按钮。我在网上搜索过,但找不到任何使图像居中的方法。

我已尝试将其设为自己的类并将 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>

图片应该在页面中间居中,这样我就可以排3了。

【问题讨论】:

    标签: html css image


    【解决方案1】:

    在 HTML 中:

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

    要使图像居中,请将左右边距设置为 auto 并使其成为 block 元素:

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

    因此,您可以在任何图像位于 div 中时将其居中。希望对您有所帮助。

    【讨论】:

      【解决方案2】:

      您可以将.btn 绝对定位到相对容器。如果您知道您想要的图片尺寸,那就更好了。

      我将如何尝试实现它:

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

      【讨论】:

        猜你喜欢
        • 2013-10-02
        • 2012-12-24
        • 2015-08-19
        • 2013-10-23
        • 2014-02-19
        • 2016-11-04
        • 2012-01-28
        • 2010-11-23
        • 2012-05-06
        相关资源
        最近更新 更多