How to dynamically center images?

Using css and javascript / jquery, how can I center the images that I showed vertically down the page? Let me draw a chart. This is what I have ...

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

This is what I want

  -------
  |     |
  |     |
  -------
-----------
|         |
|         |
-----------
   -----
   |   |
   |   |
   -----
+3
source share
3 answers

Define the following CSS for your centralized image:

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

If you put each image in <div class="img">, then set the style for them:

div.img{ 
    margin: 0 auto;
}

* Adjust the width to suit your needs.

Alternative, you can set the width <div class="img">to 100% and center the text;

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

A small fragment will be executed

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

Using jQuery, you can set the following properties:

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

All Articles