css水平居中图像

Aar*_*ron 54 html css

我试图使用CSS水平居中图像.

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

<div id="loading" class="loading-invisible">  
    <img class="loading" src="logo.png">
</div>
Run Code Online (Sandbox Code Playgroud)

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

img.loading 
{
position:absolute;
clip:rect(0px,681px,75px,180px);
}
Run Code Online (Sandbox Code Playgroud)

但是,一旦它被歪曲,我无法弄清楚如何使图像居中.

有人能帮忙吗?

Cyn*_*hia 119

试试这个CSS:

.center img {        
  display:block;
  margin-left:auto;
  margin-right:auto;
}
Run Code Online (Sandbox Code Playgroud)

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

class="center"
Run Code Online (Sandbox Code Playgroud)


Zen*_*ndy 25

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

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


Ali*_*Ali 6

您可以使用其他方法:

方法1:

这是一种简单的方法,请text-align: center;为您的父div 使用“ ”。

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

小提琴

方法2:

请检查代码:

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

小提琴

方法3:

使用“ display: flex;

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

小提琴

方法4:

您可以使用“ 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%);
}
Run Code Online (Sandbox Code Playgroud)
<div id="loading" class="loading-invisible">  
    <img class="loading" src="https://dummyimage.com/200x100/000/fff.png&text=Logo">
</div>
Run Code Online (Sandbox Code Playgroud)

小提琴

希望这会帮助你。


Pau*_*ert 5

使用margin

margin-left:auto;
margin-right:auto;
Run Code Online (Sandbox Code Playgroud)

  • 我相信您还需要一个用于 img 标签的“display:block;”。 (4认同)
  • 你还必须给它一个宽度才能工作。您还可以给包装器“text-align: center;”,只要您不将“display”更改为“inline”以外的其他内容,它本身就会使图像居中。 (2认同)