Center images in sidebar

6 Replies ·

  1. Hello –
    Finally, I’ve launched my site redo and am trying to get the last few items looking good.
    Have a look if you’d like http://gogingham.com – but please don’t tell me to change anything because I have to stop fussing with it – or as my husband calls it: obsessing 🙂
    Because my sidebars are wider with my new theme, the images – mostly jpg ads – are not centered.
    Can someone please suggest any easy way for me to do this?
    Thanks!!

  2. Justin Tadlock

    To center anything, not just images, you need a few things.

    The first, and most important, is a width. Generally, images have the `width` attribute set, so you don’t need to worry about that. Since the width doesn’t matter for images, you need to know a class or ID to target. We have that for your sidebar. So, if you want to center all images in your primary sidebar, you need this code:

    `
    #sidebar-primary img {
    margin-left: auto;
    margin-right: auto;
    }
    `

    Also, you can simply add the `aligncenter` class to an image if you’re creating the image HTML yourself like so:

    `

    `

    Now, if you want to style something that doesn’t have a width, like a `

    `, you’ll need to know the class or ID for the element. Then, you’ll need to give it a width via CSS and also apply margins like we did with images:

    `
    .some-div {
    width: 200px;
    margin-left: auto;
    margin-right: auto;
    }
    `

    That’s just about all anyone ever needs to know about centering.

  3. Bill Seymour

    @Justin-

    Is .aligncenter you refer to the Class defined in HC one-five.css? If not using one-five.css, then is this Class specified in one’s own style sheet? Thanks.

  4. Sara

    Hi Justin,
    I’m finally getting around to this centering images in the sidebar project….
    I copied and pasted the above into my CSS file – at the bottom – but it didn’t center the images.

    #sidebar-primary img {
    
    	margin-left: auto;
    	margin-right: auto;
    }

    I was able to get the html /individual image version to work:

    <img src="#" class="aligncenter" width="100" height="100" alt="" />
    So, I’m part of the way there but I would like to center all of the images.
    Thanks so much!!

  5. markmcl

    I realise this is an old post, but if anybody is searching for an answer, I found

    #sidebar-primary img {
        margin: 0 auto;
        display: block;
    }
    

    works