MynaG's Bits n Bytes

29 Nov, 2012

How to align an image in the center in HTML 5 and HTML 4

Posted by: mynag In: Solution & tips|Web developing/Coding

Long long ago…. in web development far far away….

In the past, it use to be pretty straight forward. If you worked on HTML many years ago, you may have simply placed a <center> tag to centralize images, tables etc. The <center> tag has long been depreciated since HTML 4. HTML 5 has decided to kill it, well…. not yet but sort of. It still works on HTML 5, but it is not supporting it, so we just have to move on and comply.

So here’s the alternatives to the <center> tag. To center an imag on your web page, wrap the image tag within a DIV and set add the following property in the img tag as shown below.
All images on the page will be aligned to the center.

img
{
margin:auto;
}

If you only want specific images to be aligned to the center, follow the example below.

.imgclass img
{
margin:auto;
}

<div class=”imgclass”><img src=”flower.jpg”></div>
or
<img class=”imgclass” src=”flower.jpg”>

These works on most browsers. (Firefox, Chrome, Opera, Safari) but does not work on Internet Explorer (tested not working on IE ver 7 – ver 9).
To make this compatible across all browsers including Internet Explorer, you will need to add the style property text-align:center.

The following example will work with all browsers.

<html>
<head>
<style type=”text/css”>

.imgclass
{
background-color:#1122CC;
text-align:center;
}

.imgclass img
{
margin:auto;
}

img
{
display:block;
}

</style>
<head>
<body>

<div class=”imgclass”>
<img src=”koala.jpg”>
<img src=”flower.jpg”>
</div>

</body>
</html>

The result:

Tags: , , , ,

2 Responses to "How to align an image in the center in HTML 5 and HTML 4"

1 | Pat Cummings

September 8th, 2014 at 12:51 am

Avatar

Thank you for this! It really works (and it gets rid of the EPUB Validator ERROR messages about ALIGN not being allowed in DIV…) It is truly appreciated!

2 | Clare

March 16th, 2015 at 11:33 pm

Avatar

Your are brilliant, long may you live. Thank you.

Comment Form

Categories

About

Welcome to MynaG's Bits and Bytes. My little journal containing bits and bytes of the internet, web programming and etcetera