Centering an Image with Caption and Paragraph


I’m trying to center an image on my webpage. I’ve played around with the HTML and CSS a lot and still can’t seem to get it to work. I just finished my HTML and CSS course in Codecademy and I’m not sure whether I should be using “float” or “margin”. I don’t know if I’m using the wrong things or what, but I can’t seem to get the image right in the very center of my webpage. It keeps showing up on the left. I managed to get the caption centered, but then when I changed the code again it went back to the left.

Images are inline elements so are not centerable. One approach is to wrap the img and p with a div and set the text-align on the div.


<div><img src="#" width="400" height="300"><p>caption</p></div>


div {
  text-align: center;

Another approach is to declare img as a block. Then it can have automatic margins.

<img style="display: block; margin: 0 auto;" src="#" width="400" height="300">
<p style="text-align: center;">caption</p>


Thank you. I appreciate your help.

1 Like

You’re welcome. HTML5 gives us another element that is ideal for containing an image with a caption:

  alt="An awesome picture">	
  <figcaption>Fig1. MDN Logo</figcaption>
An awesome picture Fig1. MDN Logo


Okay, so I tried your first suggestion, but it didn’t appear to do anything for me. I don’t really understand how to do this. My navigation bar is overlapping my image, and my captions do not appear. My paragraph stretches across the entire page and I’m trying to get it into an invisible box to make it more readable.

I’ll upload a couple images. One is a sketch of what I’m seeing, and the other is a sketch of what I’m trying to make.

I’m trying to make an “About” page.

In the first example, the navbar is out of normal flow so the container that follows has the static position, (0, 0) as its top left coordinate. This can be fixed with a top margin equal to the height of the navbar plus any top margin you wish to add to the content container.

We can also add more structure, but this is never a good idea since the goal is to minimize unnecessary structure. The presentation should not dictate structure. The content does that in the document outline. However, the added structure would be in the form of a div with visibility: hidden and height of the navbar + desired margin.

<nav style="position: fixed; height: 50px"></nav>
<div style="height: 60px; visibility: hidden"><div>
<div class="content"></div>
1 Like

Okay, thank you. I’ll give it a try.

1 Like