如何动态地将图像居中

How do I dynamically center images?

本文关键字:图像 何动态 动态      更新时间:2023-09-26

使用 css 和 javascript/jquery,如何将我显示的图像垂直显示在页面下方?让我画一个图表。这就是我所拥有的...

-------
|     |
|     |
-------
----------
|        |
|        |
----------
------
|    |
|    |
------

这就是我想要的

  -------
  |     |
  |     |
  -------
-----------
|         |
|         |
-----------
   -----
   |   |
   |   |
   -----

在居中图像类上设置以下 CSS:

display: block;
margin: 1em auto; /* the key here is auto on the left and right */

如果将每个图像放置在<div class="img">则设置这些图像的样式;

div.img{ 
    margin: 0 auto;
}

*调整宽度以满足您的需求。

或者,您可以将<div class="img">的宽度设置为 100% 并使文本居中;

div.img{
    width: 100%;
    text-align: center;
}

一个小片段就可以完成这项工作

display: inline-block;
margin: 1em auto;

使用 jQuery,您可以设置如下属性:

$("img#selector").css({
    'display':'inline-block',
    'margin' : '1em auto'
});