11

即使调整浏览器大小,我也想在页面中垂直和水平居中图像。

目前,我使用这个 CSS:

.centeredImage {
  position: fixed;
  top: 50%;
  left: 50%;
  margin-top: -50px;
  margin-left: -150px;
}

这个HTML:

<img class="centeredImage" src="images/logo.png">

它以 FF 为中心,但不在 IE 中(图像中心位于左上角)。有任何想法吗?

-机器人

4

13 回答 13

20

我是这样解决的:

img.class-name{

    position: absolute;
    margin: auto;
    left: 0; 
    right: 0;
    top: 0;
    bottom: 0;  
}
于 2013-05-24T08:04:34.863 回答
7

尝试使用这个:

position: absolute
于 2010-03-23T17:40:07.987 回答
3

通用的 KISS(“保持简单和愚蠢”)方式:

<p style="text-align: center;"> <img src="myImage.png" /></p>
于 2017-07-12T09:14:28.257 回答
2

这是一个棘手的方法,但它有效:

CSS:

html, body, #wrapper {
   height:100%;
   width: 100%;
   margin: 0;
   padding: 0;
   border: 0;
}
#wrapper td {
   vertical-align: middle;
   text-align: center;
}

HTML:

<html>
<body>
   <table id="wrapper">
      <tr>
         <td><img src="my_cool_image.png" alt="hello world" /></td>
      </tr>
   </table>
</body>
</html>
于 2012-03-20T04:51:03.120 回答
0
text-align:center;

vertical-align:middle;

垂直对齐

应该的伎俩

于 2010-03-23T17:39:05.103 回答
0

如果提供的答案在每个浏览器中不起作用和/或不一致,您可能需要试一试:

http://andreaslagerkvist.com/jquery/center/

text-align:center;

不过应该得到它。

于 2010-03-23T17:40:15.253 回答
0

IE 存在问题position: fixed(以及其他一百万个问题),因此如果兼容性很重要,我建议不要这样做。

position: absolute如果容器不必滚动,请使用。否则,您将需要一些 js 来在滚动时调整图像的顶部和左侧。

text-align: center如果应用于图像的容器应该可以工作,但不能应用于图像本身。但当然,这只涉及水平,而不是垂直。vertical-align: middle对我不起作用,即使有足够大的容器。

至少在我测试时,自动边距在 IE 中不起作用。

于 2010-03-23T17:42:57.277 回答
0

明确:两者;边距:自动;

于 2010-03-23T18:16:23.923 回答
0

解决方案:

 .centeredImage {
      position: absolute;
      top: 50%;
      left: 50%;
      margin-top: image-height/2;
      margin-left: image-width/2;
    }

既然你提到:

 margin-top: -50px;
 margin-left: -150px;

如果它与中心正确对齐,那么您的图像高度将为 50x2=100px; & 宽度 150x2=300px;

于 2012-02-17T16:55:37.167 回答
0
.image {
    position: fixed;
    margin: auto;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
 }
于 2014-05-23T12:50:55.593 回答
0

我做到了!这种方法坚如磐石,适用于所有主要浏览器。

style="position: fixed; margin: 0 50%; left: -850px; right: 0; top: 0; bottom: 0;" 

我只是使用了图像一半宽度的左侧,然后使用边距将其分流。工作一种享受:)

于 2014-06-24T09:33:52.940 回答
0

有一个非常简单的跨浏览器自动调整大小的方法。拍摄宽度为 200 像素的图像。取一半宽度,然后执行以下操作:

   #imgcent1 {
   left: calc (100% - 100px  /  2 );
   /*rest of code*/
   }

确保有“空白”以避免负数和正数(最好对所有操作数使用此约定)。它会自动调整大小。试试吧,希望在其他浏览器上进行测试将确保它成为预期的标准。

于 2014-08-27T13:13:25.103 回答
0

网络上的单个图像和响应式

背景图片:

/image.png

CSS:

html, body { height: 100%; margin: 0px; }

.bg-image {
    width: 100%;
    height: 100%;
    background-image: url(image.png);
    background-repeat: no-repeat;
    background-position: center center;
    background-size: contain;
    text-indent: -9999px;
}

HTML:

<body>
    <div class="bg-image">Some text not displayed</div>
</body>
于 2015-04-04T10:32:18.757 回答