May 2, 2012

How do I dynamically center images?

Question by Wilfred

With css and javascript/jquery, how do I center the images I have displayed vertically down a page? Let me draw a diagram.
This is what I have…

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

This is what I want

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

Answer by Brad

Set the following CSS on your centered image class:

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

Answer by Starx

A small snippet will get this done

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

Using jQuery you can set the properties like:

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

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!