Centering an Image with Caption and Paragraph


#1

Hi,

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.


#2

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.

html

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

css

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>

https://repl.it/Lexa


#3

Thank you. I appreciate your help.


#4

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

<figure>
  <img
  src="https://developer.cdn.mozilla.net/media/img/mdn-logo-sm.png"
  alt="An awesome picture">	
  <figcaption>Fig1. MDN Logo</figcaption>
</figure>
An awesome picture Fig1. MDN Logo

https://developer.mozilla.org/en-US/docs/Web/HTML/Element/figure


#5

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.


#6

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>

#7

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