【问题标题】:Center an image horizontally using CSS使用 CSS 将图像水平居中
【发布时间】:2020-06-21 03:01:27
【问题描述】:

我正在尝试使用 css 将图像水平居中。

我正在使用以下 HTML 代码在屏幕上显示我的图像:

<div id="loading" class="loading-invisible">  
    <img class="loading" src="logo.png">
</div>

我正在裁剪我的图像,因为我只想显示一些图像并且我正在使用以下 css:

img.loading 
{
position:absolute;
clip:rect(0px,681px,75px,180px);
}

但是我不知道如何在图像被裁剪后居中。

谁能帮忙?

【问题讨论】:

    标签: html css


    【解决方案1】:

    为你的 CSS 试试这个:

    .center img {        
      display:block;
      margin-left:auto;
      margin-right:auto;
    }
    

    然后添加到您的图像以使其居中:

    class="center"
    

    【讨论】:

    • 它对我有用。谢谢
    • 当img必须设置为position:absolute;时,此解决方案将不起作用
    • 在我的情况下,我不得不使用display:contents 而不是block
    【解决方案2】:

    像这样使用绝对位置和边距

    img.loading{
      position: absolute;
      left: 50%;
      margin-left: -(half ot the image width)px
    }
    

    【讨论】:

    • ...或者更确切地说是位置:相对?
    【解决方案3】:

    你可以使用不同的方法:

    方法一:

    这是一个简单的方法,使用“text-align: center;”作为你的父 div。

    #loading {
      text-align: center;
    }
    <div id="loading" class="loading-invisible">  
        <img class="loading" src="https://dummyimage.com/200x100/000/fff.png&text=Logo">
    </div>

    FIDDLE

    方法二:

    请检查代码:

    #loading img {
      margin: 0 auto;
      display: block;
      float: none; 
      /*width: 200px; if its a large image, it need a width for align center*/
    }
    <div id="loading" class="loading-invisible">  
        <img class="loading" src="https://dummyimage.com/200x100/000/fff.png&text=Logo">
    </div>

    FIDDLE

    方法三:

    使用“display: flex;

    #loading {
      display: flex;
      align-items: center;
      justify-content: center;
    }
    <div id="loading" class="loading-invisible">  
        <img class="loading" src="https://dummyimage.com/200x100/000/fff.png&text=Logo">
    </div>

    FIDDLE

    方法四:

    你可以使用“position: absolute;”,

    #loading {
            position: relative;
            }
    #loading img{
            position: absolute;
            top: 0;
            left: 50%;
            margin-right: -50%;
            transform: translate(-50%, 0%);
            -ms-transform: translate(-50%, 0%);
            -webkit-transform: translate(-50%, 0%);
            -moz-transform: translate(-50%, 0%);
            -o-transform: translate(-50%, 0%);
    }
    <div id="loading" class="loading-invisible">  
        <img class="loading" src="https://dummyimage.com/200x100/000/fff.png&text=Logo">
    </div>

    FIDDLE

    希望这会对你有所帮助。

    【讨论】:

      【解决方案4】:

      使用margin

      margin-left:auto;
      margin-right:auto;
      

      【讨论】:

      • 我相信您还需要一个 display:block; 作为 img 标签。
      • 你还必须给它一个宽度才能工作。你也可以给包装器text-align: center;,只要你不将display更改为inline以外的其他东西,它本身就会使图像居中。
      • 建议宽度:auto;
      猜你喜欢
      • 2011-01-29
      • 2015-06-21
      • 2019-02-10
      • 2012-03-01
      • 1970-01-01
      • 1970-01-01
      • 2018-02-01
      相关资源
      最近更新 更多