How to center image with CSS

Mike Anthony

Solid State Member
Messages
15
Location
United States
I am trying to center an image with CSS instead of using <div align="center">

My code looks like this:

<head>
<style type="text/css">
.center {
margin:auto;
width:100%
display:block;
}
</style>
</head>

<body>
<div class="center">
<img src="image.png">
</div>
</body>

Everything I read says margin:auto; should center it. Then I read you had to make it a block for it to center, and that isn't working either. Anyone know?

EDIT: text-align:center; worked perfectly. I guess that's how you do it.
 
You need to give your image an absolute width, in pixels. It should work fine.
Absolutely fine but i think that you need to Align You image in CSS declarations.
Example:

img{
width:30
height:30
align: center}
now in HTML where ever you will use <img src="abc.jpg" /> It will align it to the center of the page.
 
If you remember the old way (without the magic of CSS), it was something like this:

<p align="center">centered image here</p>

Look familiar? There's also:

<center>centered image here</center>

Of course, you don't want to do that. Both ALIGN and CENTER here are deprecated- and besides, the beauty of CSS is that it's supposed to make our lives easier, right? Now let's say I want all of the images in my blog posts to be centered nicely. Instead of having to select each one and applying the dreaded ALIGN or CENTER, all I'd have to do, really, is this:

.post-body img { display: block; margin-left: auto; margin-right: auto }

I want to give you a quick explanation of what we're doing here. The truth is that although I've been using that bit of code for a long time, I never thought to ask exactly how it worked. So here's what this does:

First, it makes the image into a block – thereby making it unnecessary to add any additional <div> or <p> tags around it. Then it tells the browser displaying it to set left and right margins to auto.

When you set these to “auto”, what you are actually doing is telling the browser that you want left and right margins to be equal – which is really another way of describing centering.
 
Back
Top Bottom