HTML and CSS Reference
Centering an Image
he float property doesn't have an option for centering an element. But while we're on the subject of aligning
images, this seems like a logical place to explain how to center an image.
As I explained in the previous chapter, you center a block-level element by giving it a width and setting its left
and right margins to auto . Browsers automatically obtain the dimensions of an image, even if you don't specify
the width and height attributes in the <img> tag. But images are inline elements, so setting the left and right
margins to auto has no effect on its own. However, all you need to do is to set the image's display property to
block , and it's centered. So, in addition to the floatleft and floatright classes, I usually add the following class
to my style sheets:
margin: 10px auto;
Figure 7-12 shows what happens in imgcentered.html when the imgcentered class is applied to the same
image as in Figures 7-3 and 7-4 .
Figure 7-12. The image is centered above its parent paragraph
Although it looks as though the image has been inserted between the two paragraphs, the <img> tag is nested
inside the beginning of the second paragraph like this:
<p> <img src="images/nice_seafront.jpg" alt="Nice seafront" width="400" height="266"
class="imgcentered"> Tear yourself away. . .</p>
So what happens if you center an image in the middle of a paragraph? Figure 7-13 shows center_break.html,
where the image has been placed at the beginning of the third sentence.