treehouse : what would you like to learn today?
Web Design Web Development iOS Development

Align an image using CSS

  • Hi I would like to center all the images in in my sidebar div but I dont know the code to do this. I know to use
    text-align: center;
    for centering text but not for an image.

    Here is what I have got so far:

    #sidebar {
    clear:right;
    float:left;
    font-size:12px;
    padding-left:15px;
    text-align:left;
    width:246px;
    }

    #sidebar img {

    }
  • this is just a guess, and I could be completely wrong (it's all trial and error for me, so I'm still learning what works and what doesn't); but try this:

    #sidebar img {
    margin: 0 auto;
    }
  • What has worked for me with aligning images especially in the sidebar has been setting it as the background-image. This maybe a newbie move being I just completed my first CSS site. I just seem to have better flexibility when I do it this way. The text seems to play better as well.
  • Actually, images are inline elements, so text-align: center; should be fine. If you have a line break above and below the image, it will be on its own line and go centered in the sidebar area.
  • I used the text-align: center; in my sidebar div which then centered the text.

    Again the god of CSS design has done it.

    Thanks Chris :P